【问题标题】:create jwt token in c# asp.net core web api [duplicate]在c#asp.net core web api中创建jwt令牌[重复]
【发布时间】:2019-08-03 21:35:06
【问题描述】:

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

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

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." });
        }
    }

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

【问题讨论】:

  • 返回的错误是什么?
  • 内部服务器错误
  • 处理请求时发生未处理的异常。 ArgumentOutOfRangeException:IDX10603:解密失败。尝试的键:'[PII 已隐藏]'.
  • 您是否正确分配了密钥?
  • 我直接放置密钥字符串而不是 _appSettings.key 但这无济于事:(

标签: c# asp.net-core jwt token


【解决方案1】:

你的逻辑是正确的!但我认为,您的密钥没有足够的字符来创建访问令牌。只需增加密钥长度即可。

更新:对于HmacSha256Signature,秘钥长度不小于128位;换句话说,它应该至少有 16 个字符。

【讨论】:

  • 轰隆隆!先生,非常感谢,这就是问题所在。最少需要 16 个符号,我只有 15 个 :) 一个符号,一切都开始完美运行!
【解决方案2】:

这是我用来构建 jwt 令牌服务器端的代码示例:

 private string BuildToken(User user)
    {
        var userSerialise = JsonConvert.SerializeObject(user);

        var claims = new[] {
            new Claim(ClaimTypes.Email, user.EmailAddress),
            new Claim(ClaimTypes.UserData, userSerialise)
        };

        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
        var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256Signature);

        var token = new JwtSecurityToken(_config["Jwt:Issuer"],
          _config["Jwt:Issuer"],
          claims,
          expires: DateTime.Now.AddMinutes(30), 
          signingCredentials: creds);

        return new JwtSecurityTokenHandler().WriteToken(token);

    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-17
    • 2019-08-03
    • 2021-07-23
    • 2019-03-09
    • 2015-06-29
    • 2020-08-22
    • 1970-01-01
    相关资源
    最近更新 更多