Web API and Identity authentication and authorization

Hi, I am trying to create a simple Web API with a controller based on a single model class and authorize the controller’s actions through Identity’s “roles” stored in a database.

I’ve added AddIdentity in the Startup.cs , created two user roles and tried to authorize an action so that it can be specifically accessed by users with one of the two roles. However, no matter what I try to use to test it, my request doesn’t even enter the the specified action (presumably because I am trying to enter the action “anonymously”). 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
        [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; })

What I expected was a JSON object, but as a result 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.

I presume that I need to create a controller that will work with accounts (login, register, logout) and that I need to login to the API first and then access the action, but I can’t think of a way to do it. The above code was enough when I put it directly in a .NET Core MVC app, but not when I make a Web API which I try to access via Postman, Swagger or a WinForms application (using Flurl or anything else).

1 Like

Have you tried asking at https://stackoverflow.com/?

Try to run application without using Authorize attribute. If it runs successfully then try to find roles and access permission how to use that.

.NET Foundation Website | Blog | Projects | Code of Conduct