猿问

在c#asp.net core web api中创建jwt令牌

我正在尝试在用户登录后创建 JWT 令牌我正在根据以下项目执行此操作: https ://github.com/CodAffection/JWT-Authentication-with-.Net-Core-Web-API-and-Angular -7/分支机构


我的应用程序在字符串上失败


var securityToken = tokenHandler.CreateToken(tokenDescriptor);


我收到错误


内部服务器错误 处理请求时发生未处理的异常。ArgumentOutOfRangeException:IDX10603:解密失败。尝试的键:'[PII 被隐藏]'


这是控制器的完整代码


   [HttpPost]

    [Route("Login")]

    //Post: /api/ApplicationUser/Login

    public async Task<IActionResult> Login(LoginModel model)

    {

        //  var user = await _userManager.FindByEmailAsync(model.UserName);

        var user = await _userManager.FindByNameAsync(model.UserName);

        if (user!=null && await _userManager.CheckPasswordAsync(user, model.Password))

        {


            var tokenDescriptor = new SecurityTokenDescriptor

            {

                Subject = new ClaimsIdentity(new Claim[]{

                    new Claim("UserID",user.Id.ToString())

                }),

                //   Expires = DateTime.UtcNow.AddMinutes(5),

                Expires = DateTime.UtcNow.AddDays(1),

                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_appSettings.key)), SecurityAlgorithms.HmacSha256Signature)

            };



            var tokenHandler = new JwtSecurityTokenHandler();

            var securityToken = tokenHandler.CreateToken(tokenDescriptor);

            var token = tokenHandler.WriteToken(securityToken);

            return Ok(new { token });   

        }

        else

        {

            return BadRequest(new { message = "username or password is incorrect." });

        }

    }

我阅读了不同的手册,但找不到问题,而且我的代码与我试图复制的项目完全相同。如果可能,请告诉我以哪种方式挖掘:)



月关宝盒
浏览 213回答 2
2回答

宝慕林4294392

你的逻辑是对的!但我认为,您的密钥没有足够的字符来创建访问令牌。只需增加密钥长度,它就可以正常工作。更新:对于HmacSha256Signature,秘钥长度不小于128位;换句话说,它应该至少有 16 个字符。

凤凰求蛊

这是我用来构建 jwt 令牌服务器端的代码示例:&nbsp;private string BuildToken(User user)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; var userSerialise = JsonConvert.SerializeObject(user);&nbsp; &nbsp; &nbsp; &nbsp; var claims = new[] {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; new Claim(ClaimTypes.Email, user.EmailAddress),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; new Claim(ClaimTypes.UserData, userSerialise)&nbsp; &nbsp; &nbsp; &nbsp; };&nbsp; &nbsp; &nbsp; &nbsp; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));&nbsp; &nbsp; &nbsp; &nbsp; var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256Signature);&nbsp; &nbsp; &nbsp; &nbsp; var token = new JwtSecurityToken(_config["Jwt:Issuer"],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; _config["Jwt:Issuer"],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; claims,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; expires: DateTime.Now.AddMinutes(30),&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; signingCredentials: creds);&nbsp; &nbsp; &nbsp; &nbsp; return new JwtSecurityTokenHandler().WriteToken(token);&nbsp; &nbsp; }
随时随地看视频慕课网APP
我要回答