Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading