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?
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.
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
{
...
}