How to authorize actions with the [Authorize(Roles)] attribute?

Bowser

I am trying to create a simple Web API with a controller based on a single model class.

I've added AddIdentity in the Startup.cs, created two user roles and tried to authorize an action in the controller so that it can be specifically accessed by one of the two roles. However, no matter what I try to use to test it, it always results in an error where the response states that the server doesn't even enter the the specified action. So far I tried using Postman and Swagger UI, neither of which provided me with a proper response.

The action that I am trying to access would be this one:

        // GET api/media
        [HttpGet]
        [Authorize(Roles = "Member")]
        public IEnumerable<Media> Get()
        {
            return _mediaData.Get();
        }

Here's how I added Identity support in the Startup.cs class:

services.AddIdentity<User, Role>(config => { config.SignIn.RequireConfirmedEmail = false; })
                .AddEntityFrameworkStores<ApplicationDbContext>()
                //.AddDefaultUI()
                .AddDefaultTokenProviders();

What I expected was a JSON object, but as a results Swagger provides me with an error which states that it was expected for me to login, but I am not sure how I can do that. I suppose I need to learn more stuff regarding the SignIn and UserManager, but I have no idea how I would "login and open a session" (that's what I assume would solve the problem) and I've been unable to find any resource explaining how to do it, much less how get the result via Postman or Swagger UI.

TheDoomDestroyer

Swagger UI provides an authentication method for you, for which you need to make a few changes to your Startup.cs. For that, modify your ConfigureServices method to something like:

services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
    c.AddSecurityDefinition("basic", new BasicAuthScheme() { Type = "basic" }); // Depending on your authentication, this will look different, but the most common one would be the Basic Authentication, so perhaps play with that or go with what you already had in mind
    c.DocumentFilter<BasicAuthDocumentFilter>();
});

If you go with the Basic Authentication, you can use the code below to provide Swagger with the document filter (BasicAuthDocumentFilter), which may look like:

public class BasicAuthDocumentFilter : IDocumentFilter
{
    public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context)
    {
        var securityRequirements = new Dictionary<string, IEnumerable<string>>()
        {
            { "basic", new string[] { } }
        };
        swaggerDoc.Security = new[] { securityRequirements };
    }
}

To use it, simply open Swagger UI and you should see an Authorize button just below the title. Click on it and provide the necessary authentication info it requires and you should be good to go.

As for ASP Identity, it's not very common to use ASP Identity for Web APIs if I am not mistaken. I would personally switch over to Basic or OAITH since those sound more natural when talking about APIs.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How to authenticate and authorize in GitHub Actions chains of module source calls

Not Found for actions with Authorize attribute while using identity in asp.net core

How does [Authorize] attribute know if a user has a role?

HotChocolate with Authorize attribute, how to get currently logged on user?

Authorize Attribute with Multiple Roles

Authorize attribute and changed database

Mvc Authorize attribute is not working

Extending the Authorize attribute

Check authorize in SignalR attribute

PrincipalPermission vs Authorize Attribute?

custom authorize attribute not working

How to create a custom attribute that will redirect to Login if it returns false, similar to the Authorize attribute - ASP.NET MVC

Azure API Management - Authorize Attribute

C# Authorize Attribute Logic

WebApi Custom Authorize Attribute not working

Authorize attribute ReturnUrl not working as expected

Thymeleaf is not parsing "sec:authorize" attribute

Authorize attribute always returns 401

Use [Authorize] Attribute Without Identity?

Problems with custom authorize attribute on published

Authorize attribute not working MVC 5

Change default reroute of Authorize attribute

Authenticate & Authorize User Before Hitting Actions

How to make SCHTASKS /Query display the "multiple actions" attribute in query result?

How would I dynamically set the allowed Role or Policy for an Authorize View tag or attribute in Blazor from appsettings?

How do I create a custom Authorize attribute that does not depend on claims in ASP.NET Core?

How do identity server validate the token at API or when we use Authorize attribute?

How to override Authorize attribute in ASP.MVC 5 with multiple authorization conditions?

How to know if the controller or action has Authorize attribute using HttpContext.Features.Get<IExceptionHandlerPathFeature>()?