Configuring custom claims on users

This document explains how to configure custom claims on users with Identity Platform. Custom claims are inserted into user tokens during authentication. Your app can use these claims to handle complex authorization scenarios, such as restricting a user's access to a resource based on their role.

Before you begin

Using custom claims

To preserve security, set custom claims using the Admin SDK on your server. The following example shows how to use custom claims with Node.js; the Admin SDK reference includes examples for other languages.

  1. Set the custom claim you want to use. In the following example, a custom claim is set on the user to describe that they're an administrator:

    // Set admin privilege on the user corresponding to uid.
    admin.auth().setCustomUserClaims(uid, {admin: true}).then(() => {
      // The new custom claims will propagate to the user's ID token the
      // next time a new one is issued.
    });
    
  2. Validate the custom claim the next time it's sent to your server:

    // Verify the ID token first.
    admin.auth().verifyIdToken(idToken).then((claims) => {
      if (claims.admin === true) {
        // Allow access to requested admin resource.
      }
    });
    
  3. To determine what custom claims are present for a user:

    // Lookup the user associated with the specified uid.
    admin.auth().getUser(uid).then((userRecord) => {
      // The claims can be accessed on the user record.
      console.log(userRecord.customClaims.admin);
    });
    

Custom claims are extremely powerful, but you should note the following:

  • Custom claims cannot exceed 1000 bytes in size. Attempting to pass claims larger than 1000 bytes will result in an error.
  • Custom claims are inserted into the user JWT when the token is issued. New claims are not available until the token is refreshed. You can refresh a token silently by calling user.getIdToken(true).
  • To maintain continuity and security, only set custom claims in a secure server environment.

What's next