사용자에 대한 커스텀 클레임 구성

이 문서에서는 Identity Platform을 사용하여 사용자에 대한 커스텀 클레임을 구성하는 방법을 설명합니다. 커스텀 클레임은 인증 중에 사용자 토큰에 삽입됩니다. 앱에서 이러한 클레임을 사용하여 역할을 기준으로 리소스에 대한 사용자의 액세스 권한을 제한하는 등의 복잡한 승인 시나리오를 처리할 수 있습니다.

커스텀 클레임 설정

보안을 유지하려면 서버에서 Admin SDK를 사용하여 커스텀 클레임을 설정하세요.

  1. 아직 설치하지 않았으면 Admin SDK를 설치합니다.

  2. 사용하려는 커스텀 클레임을 설정합니다. 다음 예시에서는 사용자가 관리자임을 설명하는 커스텀 클레임을 설정합니다.

    Node.js

    // Set admin privilege on the user corresponding to uid.
    
    getAuth()
      .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.
      });

    Java

    // Set admin privilege on the user corresponding to uid.
    Map<String, Object> claims = new HashMap<>();
    claims.put("admin", true);
    FirebaseAuth.getInstance().setCustomUserClaims(uid, claims);
    // The new custom claims will propagate to the user's ID token the
    // next time a new one is issued.

    Python

    # Set admin privilege on the user corresponding to uid.
    auth.set_custom_user_claims(uid, {'admin': True})
    # The new custom claims will propagate to the user's ID token the
    # next time a new one is issued.

    Go

    // Get an auth client from the firebase.App
    client, err := app.Auth(ctx)
    if err != nil {
    	log.Fatalf("error getting Auth client: %v\n", err)
    }
    
    // Set admin privilege on the user corresponding to uid.
    claims := map[string]interface{}{"admin": true}
    err = client.SetCustomUserClaims(ctx, uid, claims)
    if err != nil {
    	log.Fatalf("error setting custom claims %v\n", err)
    }
    // The new custom claims will propagate to the user's ID token the
    // next time a new one is issued.

    C#

    // Set admin privileges on the user corresponding to uid.
    var claims = new Dictionary<string, object>()
    {
        { "admin", true },
    };
    await FirebaseAuth.DefaultInstance.SetCustomUserClaimsAsync(uid, claims);
    // The new custom claims will propagate to the user's ID token the
    // next time a new one is issued.
  3. 다음 번에 서버에 전송될 때 커스텀 클레임의 유효성을 검사합니다.

    Node.js

    // Verify the ID token first.
    getAuth()
      .verifyIdToken(idToken)
      .then((claims) => {
        if (claims.admin === true) {
          // Allow access to requested admin resource.
        }
      });

    Java

    // Verify the ID token first.
    FirebaseToken decoded = FirebaseAuth.getInstance().verifyIdToken(idToken);
    if (Boolean.TRUE.equals(decoded.getClaims().get("admin"))) {
      // Allow access to requested admin resource.
    }

    Python

    # Verify the ID token first.
    claims = auth.verify_id_token(id_token)
    if claims['admin'] is True:
        # Allow access to requested admin resource.
        pass

    Go

    // Verify the ID token first.
    token, err := client.VerifyIDToken(ctx, idToken)
    if err != nil {
    	log.Fatal(err)
    }
    
    claims := token.Claims
    if admin, ok := claims["admin"]; ok {
    	if admin.(bool) {
    		//Allow access to requested admin resource.
    	}
    }

    C#

    // Verify the ID token first.
    FirebaseToken decoded = await FirebaseAuth.DefaultInstance.VerifyIdTokenAsync(idToken);
    object isAdmin;
    if (decoded.Claims.TryGetValue("admin", out isAdmin))
    {
        if ((bool)isAdmin)
        {
            // Allow access to requested admin resource.
        }
    }
    
  4. 사용자에게 제공할 커스텀 클레임을 확인하려면 다음을 수행합니다.

    Node.js

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

    Java

    // Lookup the user associated with the specified uid.
    UserRecord user = FirebaseAuth.getInstance().getUser(uid);
    System.out.println(user.getCustomClaims().get("admin"));

    Python

    # Lookup the user associated with the specified uid.
    user = auth.get_user(uid)
    # The claims can be accessed on the user record.
    print(user.custom_claims.get('admin'))

    Go

    // Lookup the user associated with the specified uid.
    user, err := client.GetUser(ctx, uid)
    if err != nil {
    	log.Fatal(err)
    }
    // The claims can be accessed on the user record.
    if admin, ok := user.CustomClaims["admin"]; ok {
    	if admin.(bool) {
    		log.Println(admin)
    	}
    }

    C#

    // Lookup the user associated with the specified uid.
    UserRecord user = await FirebaseAuth.DefaultInstance.GetUserAsync(uid);
    Console.WriteLine(user.CustomClaims["admin"]);

커스텀 클레임을 설정할 때는 다음 사항에 유의하세요.

  • 커스텀 클레임은 크기가 1,000바이트를 초과할 수 없습니다. 1,000바이트를 초과하는 클레임을 전달하려고 하면 오류가 발생합니다.
  • 커스텀 클레임은 토큰이 발급될 때 사용자 JWT에 삽입됩니다. 토큰이 새로고침될 때까지 새 클레임을 사용할 수 없습니다. user.getIdToken(true)을 호출하여 자동으로 토큰을 새로고침할 수 있습니다.
  • 연속성과 보안을 유지하려면 안전한 서버 환경에서 커스텀 클레임만 설정하세요.

다음 단계

  • 커스텀 클레임을 설정하는 데도 사용할 수 있는 차단 함수에 대해 자세히 알아보세요.
  • Identity Platform 커스텀 클레임에 대한 자세한 내용은 Admin SDK 참조 문서를 참조하세요.