简体   繁体   中英

Getting 401 unauthorized ASP.NET CORE 6

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

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 
            };
        });

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM