xchrisbradley
xchrisbradley

Reputation: 503

Authenticate an user on firebase rest api security rules

I have a basic security rule that checks if the user is authenticated.

{
  "rules": {
    "users": {
      "$user_id": {
        ".write": "auth != null"
      }
    }
  }
}

How can I get firebase security rules to acknowledge auth data from cloud functions when sent an access token from the client app.

Request Method = Post

import * as admin from 'firebase-admin'

const DEPLOYED = false;

admin.initializeApp()

const ValidateToken = (request: any, response: any) => {

    const params = {
        a: request.body.token, // Client Validation
    }

    const ValidateToken = admin.auth().verifyIdToken(params.a).catch((error) => { throw { Message:error }});

    return Promise.all([ValidateToken]).then((res: any) => {
        return DEPLOYED ? res : response.status(200).json(res);
    }).catch(error => {
        return DEPLOYED ? error : response.status(400).json(error);
    });
}

export default ValidateToken;

Gives 200 responses and user data.

Update Username

import FBApp from '../utils/admin'

FBApp

const UpdateUsername = (request: any, response: any) => {

    const params = {
        a: request.body.UID,
        b: request.body.username
    }

    const UpdateProfile = FBApp.database().ref('users').child(`${params.a}/username`).set(`@${params.b}`).catch((error) => { throw { Message:error }});

    return Promise.all([UpdateProfile]).then((res: any) => {
        response.status(200).json(res);
    }).catch(error => {
        response.status(400).json(error);
    });
}

export default UpdateUsername;

Gives permission denied

Upvotes: 0

Views: 384

Answers (1)

gso_gabriel
gso_gabriel

Reputation: 4670

For the Cloud Functions to work and run properly, they have administrative rights, which means, that they "bypass" the security rules set on your Firebase. For this reason, you just need to have your rules set to secure your application from unauthenticated users.

Besides that, I found this article below, which should provide you more information as well, on the use of rules with Cloud Functions and Firebase.

Let me know if the information helped you!

Upvotes: 1

Related Questions