Search code examples
aws-lambdaamazon-cognito

NET 6 Lambda : how to add roles to AWS Cognito?


I develop NET 6 AWS Lambda. I need add role-based access to controllers methods like

[Authorize(Policy = "SuperAdmin ")]
public class SecuredController : Controller
{}
[Authorize(Policy = "Admin ")]
public class LessSecuredController : Controller
{}

I use AWS Cognito. Where can set roles for users in AWS Cognito? and how they will be applied?


Solution

  • You could use Policy-based authorization, which is very similar to Role based authorization.

    To enable Policy-based authorization with Cognito, you need to leverage Cognito Groups. This requires you to create a Cognito group first.

    1. Create a new Cognito group

    1. Go to the Amazon Cognito console, and choose the user pool that you created earlier.
    2. Choose the Groups tab, and then choose Create a group.
    3. On the Create a group page, in Group name, enter Admin for your new group.
    4. Leave everything with defaults.
    5. Choose Create to confirm.

    2. Add user to the Cognito Group

    1. Choose the Users tab, and then choose a user.
    2. On the user detail page, scroll down to the bottom, and click on Add user to group button in Group memberships section.
    3. Add the user to the previously created Admin group.

    3. Modifications in Code

    After that, go to your Program.cs file, add the instructed code block in your file.

    var builder = WebApplication.CreateBuilder(args);
    
    // ------ Add this code block -----
    builder.Services.AddAuthorization(options =>
    {
        options.AddPolicy("AdminOnly", policy => policy.RequireClaim("cognito:groups", "Admin"));
    });
    

    Finally, modify the [Authorize] attribute to include the policy name.

    [Authorize(Policy = "AdminOnly")]
    public class HomeController : Controller
    {
      ...
    }