0
0
FirebaseHow-ToBeginner · 3 min read

How to Use request.auth in Firebase Security Rules

Use request.auth in Firebase security rules to check if a user is signed in and to access their authentication info. For example, request.auth != null ensures only authenticated users can read or write data. You can also check user IDs with request.auth.uid to restrict access to specific users.
📐

Syntax

The request.auth object in Firebase rules represents the user's authentication state. It is null if the user is not signed in. When signed in, it contains details like uid (user ID) and token (user claims).

Common checks include:

  • request.auth != null: User is signed in.
  • request.auth.uid == "userId": User ID matches.
firebase
allow read, write: if request.auth != null;

allow update: if request.auth != null && request.auth.uid == resource.data.ownerId;
💻

Example

This example shows a Firestore rule that allows only authenticated users to read and write their own documents. Each document has an ownerId field matching the user's UID.

firebase
service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{userId} {
      allow read, write: if request.auth != null && request.auth.uid == userId;
    }
  }
}
Output
If a user is signed in with UID 'abc123', they can read and write only the document at /users/abc123. Other users or unauthenticated requests are denied.
⚠️

Common Pitfalls

Common mistakes when using request.auth include:

  • Not checking if request.auth is null before accessing uid, causing errors.
  • Allowing access without verifying the user's UID, which can expose data to others.
  • Confusing request.auth.uid with document fields; always compare carefully.
firebase
/* Wrong: No null check */
allow read: if request.auth.uid == resource.data.ownerId;

/* Right: Check for authentication first */
allow read: if request.auth != null && request.auth.uid == resource.data.ownerId;
📊

Quick Reference

ExpressionMeaning
request.auth != nullUser is signed in
request.auth == nullUser is not signed in
request.auth.uidUser's unique ID
request.auth.token.email_verifiedUser's email is verified
request.auth.token.admin == trueUser has admin claim

Key Takeaways

Always check if request.auth is not null before accessing user info.
Use request.auth.uid to restrict data access to the authenticated user.
Never allow access without verifying user identity in rules.
request.auth contains user authentication details like uid and claims.
Test your rules to ensure only authorized users can access data.