Reputation: 506
Im implementing role based authentication in ASP.NET CORE 6, and im getting 401 Unauthorized from Postman. i have included the bearer token, i have checked it in jwt.io and it is valid. but it still shows up 401 unauthorized. here is my startup.cs file
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration.GetSection("AppSettings:Token").Value)),
ValidateIssuer = false,
ValidateAudience = false
};
});
builder.Services.AddControllersWithViews();
builder.Services.AddRazorPages();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseWebAssemblyDebugging();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseBlazorFrameworkFiles();
app.UseStaticFiles();
app.MapRazorPages();
app.UseAuthentication();
app.UseRouting();
app.UseAuthorization();
app.MapControllers();
app.MapFallbackToFile("index.html");
app.Run();
and here is a controller method
[HttpGet("onlinedrivers"), Authorize]
public async Task<ActionResult> GetOnlineDrivers()
{
var result = await _driverServices.GetOnlineDrivers();
return Ok(result);
}
i included the jwt bearer token as follows
i dont know what im doing wrong
Upvotes: 3
Views: 14150
Reputation: 11
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration.GetSection("AppSettings:Token").Value)),
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = false // you dont want to validate lifetime
};
});
Upvotes: 1
Reputation: 506
It it fixed, found out i had commented out the token expiration date when i was creating it. i checked the log thanks to gunr2171 and it said
Bearer error="invalid_token", error_description="The token has no expiration"
so when i added the expiration date, it worked.
Upvotes: 2