Cognito add Custom Claims to Tokens

0

I'm working with Cognito and I have a role-based authorization flow in my backend application. I would like to add the role of a customer to the token, so that I can easily manage the guards of the API endpoints. I found out Cognito doesn't provide such a customization out of the box, and the suggestion is to use a Lambda function that will do the trick. I spinned up a Lambda and I'm sending the role I want to include in the token (by updating userAttributes, which is weird because I can only do it after user is authenticated) but it doesn't seem to do the trick. Is there a way to achieve such a thing? If so, how can I do it? Thanks in advance!

已提問 10 個月前檢視次數 609 次
1 個回答
0

I believe what you are trying to do is trigger the lambda function before the user is authenticated, which requires a pre-authentication trigger. In your Lambda function, you can update the user attributes before the token is generated. Use the event.request.userAttributes parameter to access the user attributes. Update the cognito:groups attribute with the desired role value. I’ve included a link that describes the pre-authentication triggers, as well as the documentation for user-identity-pool integration with lambda triggers.

Pre Authenitcation https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-pre-authentication.html Lambda Triggers & Identity Pools https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools-working-with-aws-lambda-triggers.html (https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools-working-with-aws-lambda-triggers.html)

Hope this helps!

AWS
已回答 10 個月前
  • Thanks for your answer, Aafant!

    A couple of things: I'm using amazon-cognito-identity-js lib to handle the cognito stuff in my NestJS app. There is a method called updateAttributes that can only be invoked by an authenticated user, so I first authenticate the user, then I call the updateAttributes and authenticate the user again (this is very confusing, but was the only way I found to update the userAttributes). Also, the Lambda is triggered automatically by the authenticateUser. I'm logging the event.request.userAttributes and I'm able to see the attribute I want to set. Everything seems to be okay, but the token is not getting the custom claims. By the way, I followed this tutorial from AWS: https://aws.amazon.com/blogs/mobile/how-to-use-cognito-pre-token-generators-to-customize-claims-in-id-tokens/

您尚未登入。 登入 去張貼答案。

一個好的回答可以清楚地回答問題並提供建設性的意見回饋,同時有助於提問者的專業成長。

回答問題指南