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.
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.
Comments