Rafael Zasas
Rafael Zasas

Reputation: 993

Firestore security rules request.auth is always null

I am unsuccessfully trying to tighten Firestore security with custom claims.

versions:

I have verified that my custom claims are set as they work as expected for certain collections/requests, specifically ones coming from NextJs Server Side Rendered functions.

I have tried:

From the security rules debug - request.auth is null

debug-rules

Update:

I see from the rules usage on the firebase console that the rules were treated as errors and not denies.

I have found strange behavior.

I am successfully able to use custom claims for any collection other than 'blog'.

Successful rule matching tags:

successful

I'm starting to think it has something to do with NextJs Server Side Rendering using getServerSideProps()

My code to retrieve blog entries:

export async function getServerSideProps(context) {
  const posts: BlogPost[] | any = await GetBlogPosts();
  return {
    props: {posts}, // will be passed to the page component as props
  };
}

interface extendedBlogPosts extends BlogPost {
  ['key']: string;
  id: string;
}
interface BlogPageProps {
  posts: extendedBlogPosts[];
  userProps: {user: UserInfo; userData: UserData};
}

Upvotes: 2

Views: 1658

Answers (2)

Frank van Puffelen
Frank van Puffelen

Reputation: 598623

It sounds like the code in getServerSideProps runs in a trusted environment and accesses Firestore using an Admin SDK. If that is the case then the behavior you are seeing is expected, as the Admin SDKs access the database with elevated/administrative privileges and not as a specific user, and bypass all security rules.


Even if you're not using the Admin SDK, if that code runs in the server using the regular JavaScript SDK (or the one for Node.js, but not for administrative usage), your code is executing in a different environment than where the user signed in. So unless you've signed the user into the server-side code too, it will run without a signed in user, and thus the request.auth variable in your rules will be null.

Upvotes: 3

Frank van Puffelen
Frank van Puffelen

Reputation: 598623

The current user information is stored in request.auth, not in request.resource.auth as you are using in your first and last screenshots.

Upvotes: 0

Related Questions