C#C
C#3y ago
_vegabyte_

✅ JWT Authorization Issue with .NET Core Web API

Hello everyone,
I am currently working on an ASP.NET Core Web API that uses JWT for authorization. I have a GetAllUsersAsync endpoint that needs to be authorized but I am facing some issues. Here is the code for the endpoint:

[HttpGet("GetAllUsers")]
[Authorize]
public async Task<IActionResult> GetAllUsersAsync([FromQuery] UserParams userParams)
{
    // Implementation here...
}

Here is my JWT authentication setup:
builder.Services.AddAuthentication(authOptions =>
{
    authOptions.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    authOptions.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(jwtOptions =>
{
    var key = builder.Configuration.GetValue<string>("JwtConfig:Key");
    var keyBytes = Encoding.ASCII.GetBytes(key);

    jwtOptions.SaveToken = true;
    jwtOptions.RequireHttpsMetadata = false;
    jwtOptions.TokenValidationParameters = new TokenValidationParameters
    {
        IssuerSigningKey = new SymmetricSecurityKey(keyBytes),
        ValidateAudience = true,
        ValidateLifetime = true,
        ValidateIssuer = false,
        ClockSkew = TimeSpan.Zero,
        
        ValidIssuer = builder.Configuration["JwtConfig:Issuer"],
        ValidAudience = builder.Configuration["JwtConfig:Audience"]
    };
});

The problem I'm encountering is when I try to access the GetAllUsersAsync endpoint with a valid token, I still get unauthorized responses. It seems the token isn't correctly validated or there's something wrong with my setup.
Would appreciate any ideas or suggestions on what might be wrong.
Thank you in advance.
Was this page helpful?