How can I troubleshoot a "401 unauthorized" error when generating a JWT token in ASP.NET?

I’m trying to generate a JWT token in my ASP.NET API using the following code in my Program.cs file:

var key = Encoding.ASCII.GetBytes(Settings.Secret);
builder.Services.AddAuthentication(x =>
{
    x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(x =>
{
    x.RequireHttpsMetadata = false;
    x.SaveToken = true;
    x.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = new SymmetricSecurityKey(key),
        ValidateIssuer = false,
        ValidateAudience = false
    };
});
app.UseAuthorization();
app.UseAuthentication();

I then use the following code to generate the token:

namespace DeliveryAPI.Services
{
    public class TokenService
    {
        public static string GenerateToken(EstablishmentLoginDTO request)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            var key = Encoding.ASCII.GetBytes(Settings.Secret);
            var tokenConfig = new SecurityTokenDescriptor
            {
                Subject = new System.Security.Claims.ClaimsIdentity(new Claim[]
                {
                    new Claim("email", request.Email.ToString())
                }),
                Expires = DateTime.UtcNow.AddHours(2),
                SigningCredentials = new SigningCredentials(
                    new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256)
            };

            var tokenHandler = new JwtSecurityTokenHandler();
            var token = tokenHandler.CreateToken(tokenConfig);
            var tokenString = tokenHandler.WriteToken(token);

            return tokenString;
        }
    }
}

I then use the generated token in the "Authorization" header of my requests, but I always get a "401 unauthorized" error. I’m using ASP.NET 7.

In the frontend, I’m using the token in the request header like this:

"Authorization": `Bearer ${token}`

And the same issue on postman using my JWT token.

What could be causing this error, and how can I troubleshoot it?

>Solution :

You need to fix the order of the auth middlewares.

It is important to first do the authentication and if authenticated then do the authorization.

So all you need to do is change the auth lines to be:

app.UseAuthentication();
app.UseAuthorization();

Leave a Reply