CarterCommunity / Carter

Carter is framework that is a thin layer of extension methods and functionality over ASP.NET Core allowing code to be more explicit and most importantly more enjoyable.
MIT License
2.05k stars 172 forks source link

How to Authorize Endpoint for specific Role #316

Closed xts-velkumars closed 1 year ago

xts-velkumars commented 1 year ago

@jchannon, Is there any example how to use "RequiresClaims"

I couldn't find any Extension Method for "RequiresClaims" Carter V7.0.0

Basically, I want to achieve below

[Route("/api/users")]
[AuthorizeRole(RoleType.SuperAdmin)]
public async Task<IEnumerable<UsersViewModel>> GetUsers(CancellationToken cancellationToken)
{
       return await mediator.Send(new UsersQuery(), cancellationToken);
}
jchannon commented 1 year ago

Use RequireAuthorization on your route definition or on the module in it's constructor and pass in your roles/policies:

 app.MapGet("/", () =>
        {

            return "Hi";
        }).RequireAuthorization();
public DirectorsModule() : base("/directors")
    {
         this.RequireAuthorization();
}