3

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 Token included

i dont know what im doing wrong

3
  • Why do you have a middleware between UseAuthentication and UseAuthorization? Normally UseRouting goes before them both. Commented Apr 30, 2022 at 19:44
  • i was using that, i just saw an answer on this site that implemented that structure, still doesn't work. Commented Apr 30, 2022 at 19:45
  • 1
    Do you need to configure the options.Authority (or options.Audience, though you've configured the validator not to check it) inside AddJwtBearer? Also go into your appsettings.Development.json file and change the logging to Debug and watch the console output to help find out why auth isn't catching. Commented Apr 30, 2022 at 19:48

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.