I have this in my Startup.cs in the ConfigureServices:
services.ConfigureJwt(Configuration);
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Backend.API", Version = "v1" });
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Description = "JWT Authorization header using the Bearer scheme (Example: 'Bearer 12345abcdef')",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey,
Scheme = "Bearer"
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
Array.Empty<string>()
}
});
});
I have this in my Startup.cs in the Configure:
app.UseCors("EnableCors");
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
This is my service extension:
public static void ConfigureJwt(this IServiceCollection services, IConfiguration configuration)
{
var settings = new JwtSettings();
settings.Key = configuration["JwtSettings:key"];
settings.Audience = configuration["JwtSettings:audience"];
settings.Issuer = configuration["JwtSettings:issuer"];
settings.MinutesToExpiration = Convert.ToInt32(
configuration["JwtSettings:minutesToExpiration"]);
services.AddSingleton(settings);
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = "JwtBearer";
options.DefaultChallengeScheme = "JwtBearer";
})
.AddJwtBearer("JwtBearer", jwtBearerOptions =>
{
jwtBearerOptions.RequireHttpsMetadata = false;
jwtBearerOptions.SaveToken = true;
jwtBearerOptions.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = settings.Issuer,
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(settings.Key)),
ValidAudience = settings.Audience,
ClockSkew = TimeSpan.FromMinutes(
settings.MinutesToExpiration)
};
});
}
and in my Sagger UI login, this is the reply I get:
{
"userId": 1,
"userName": "user",
"firstName": "My FirstName",
"middleName": "A.",
"lastName": "My LastName",
"bearerToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJqdWFuIiwianRpIjoiNmQwNjQ4ZWMtOGI4YS00YTBkLTlmYmItZTliYWFmNzdmZjI2IiwiVXNlcklkIjoiMSIsIkZpcnN0TmFtZSI6Imp1YW4iLCJNaWRkbGVOYW1lIjoiQS4iLCJMYXN0TmFtZSI6IkRlbGEgQ3J1eiIsImh0dHA6Ly9zY2hlbWFzLm1pY3Jvc29mdC5jb20vd3MvMjAwOC8wNi9pZGVudGl0eS9jbGFpbXMvcm9sZSI6WyJVc2VyIiwiQWRtaW4iXSwiZXhwIjoxNjA2OTc4MjcyLCJpc3MiOiJodHRwczovL2xvY2FsaG9zdDo0NDM2NiIsImF1ZCI6IkdlbmVyYWxUZW1wbGF0ZSJ9.MMnu-suoae7U3QnXJTa9wI2xDUtdDJTtc63KWyd3bZM",
"isAuthenticated": true,
"claims": [
"User",
"Admin"
]
}
Why is it that I still get this error whenever I try to run an endpoint with [Authorize(Roles = "Admin")]
access-control-allow-origin: *
date: Thu03 Dec 2020 06:42:05 GMT
server: Microsoft-IIS/10.0
status: 401
www-authenticate: Bearer
x-powered-by: ASP.NET
This is the endpoint I am trying to run:
[HttpPost]
[Authorize(Roles = "Admin")]
public async Task<IActionResult> AddCategory(Category model)
{
var cm = new CategoryManager(context);
var result = await cm.Create(model);
if (result > 0)
{
return StatusCode(StatusCodes.Status201Created, model);
}
return StatusCode(StatusCodes.Status400BadRequest, model);
}
I was having this issue because I was just copy and pasting the "bearerToken" value in the Authorize of swagger. What I should do is copy the "bearerToken" value but add "Bearer " at the beginning.