简体   繁体   English

为什么我在 Asp.Net CORE 中使用 JWT 获得 401 未经授权的工作?

[英]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).我正在尝试使用 JsonWebTokens(JWT) 在 Asp.net CORE 中进行用户身份验证。

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.当我在我的应用程序中运行登录方法时,令牌已正确生成,但是,当我尝试将 go 设置为受[Authorize]属性限制的方法时,我收到 401 未经授权的错误。

Bearer error=\"invalid_token\", error_description=\"The signature is invalid\" Bearer error=\"invalid_token\", error_description=\"签名无效\"

This is how I configured in the ConfigureServices method in Startup :这就是我在StartupConfigureServices方法中配置的方式:

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 :这就是我在Startup的配置中的配置方式:

app.UseAuthentication();

This is the token generation in the LoginController :这是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这是我限制的 class ,与拒绝访问相同

[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.我正在使用 postman 对此进行测试,并且我已经添加了相应的 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.令牌中的key与您在配置中设置的不匹配。 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..".从您共享的代码中,在生成令牌时,您将签名密钥用作“1234..”,但在 startup.cs 中进行验证时,您正在使用“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)如果是实时的,请使用非对称密钥(公钥和私钥)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM