简体   繁体   中英

Why I'm getting a 401 unauthorized working with JWT in Asp.Net CORE?

I'm trying to make a User Authentication in Asp.net CORE using JsonWebTokens(JWT).

When I run the login method in my app the token is correctly generated, but, when I try to go to a method restricted with [Authorize] attribute, I get a 401 unauthorized error.

Bearer error=\"invalid_token\", error_description=\"The signature is invalid\"

This is how I configured in the ConfigureServices method in Startup :

services.AddAuthentication(x =>
        {
            x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

        }).AddJwtBearer(x =>
        {
            var key = Encoding.ASCII.GetBytes("asdwda1d8a4sd8w4das8d*w8d*asd@#");
            var signingKey = new SymmetricSecurityKey(key);

            x.RequireHttpsMetadata = false;
            x.SaveToken = true;
            x.TokenValidationParameters = new TokenValidationParameters()
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = signingKey,
                ValidAudience = "Audience",
                ValidIssuer= "Issuer",
                ValidateIssuer = false,
                ValidateAudience = false
            };
        });

And this is how I configured in the configure in Startup :

app.UseAuthentication();

This is the token generation in the LoginController :

                var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim("UserID", login.IdUsuario.ToString())
                }),
                Expires = DateTime.UtcNow.AddDays(1),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.ASCII.GetBytes("asdwda1d8a4sd8w4das8d*w8d*asd@#")), 
            SecurityAlgorithms.HmacSha256Signature)
            };
            var tokenHandler = new JwtSecurityTokenHandler();
            var securityToken = tokenHandler.CreateToken(tokenDescriptor);
            var token = tokenHandler.WriteToken(securityToken);

            return Ok( new { token } );

And this is the class that I restricted, the same that is denying the access

[HttpGet]
[Authorize]
[Route("Profile")]
public IActionResult Profile()
{
     string userID = User.Claims.First(c => c.Type == "UserID").Value;
     var resultado = _UsuarioServicio.Profile(int.Parse(userID));
     return Ok(resultado);
}

I'm testing this with postman and I've already added the corresponding header.

Thank you so much for taking the time to look at this!

The key in your token does not match what you are setting in the configuration. They have to match perfectly.

Please use the same symmetric key while generating token & validating token. From the code you shared, while generating token, you are using the signing keys as "1234.." but while validating in startup.cs you are using "ab de..". That's why, it is complaining that signature is not valid as both the key don't match.

Also, please store the keys in a secured configuration file. If it is for a real time, please use asymmetric keys (public key & private key)

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