C#Jwt令牌生成失败,asp.net core 2.2

时间:2019-02-02 11:08:14

标签: c# authentication jwt

我正在尝试为userId生成令牌,很遗憾,我无法使其正常工作。

这是我的JwtTokenGenerator类

namespace WebApiDocker.Config.Jwt
{
    //https://www.c-sharpcorner.com/article/jwt-json-web-token-authentication-in-asp-net-core/
    public class JwtTokenProvider
    {
        private readonly JwtSecurityTokenHandler _jwtTokenHandler;
        private readonly AppSettings _appSettings;

        public JwtTokenProvider(JwtSecurityTokenHandler jwtTokenHandler, AppSettings appSettings) 
        {
            _jwtTokenHandler = jwtTokenHandler;
            _appSettings = appSettings;
        }

        public string GenerateTokenForUser(int userId)
        {
            var secret = Encoding.ASCII.GetBytes(_appSettings.Secret);
            Console.WriteLine($"Key {secret}");
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, userId.ToString())
                }),
                Expires = DateTime.UtcNow.AddDays(7),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(secret), SecurityAlgorithms.HmacSha256Signature)
            };
            var token = _jwtTokenHandler.CreateToken(tokenDescriptor);
            return _jwtTokenHandler.WriteToken(token);

        }

        private string GenerateTokenForNewUser()
        {
            var securityKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(_appSettings.Secret));
            var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature);
            var jwtToken = new JwtSecurityToken("", "", null, DateTime.Now, DateTime.Now.AddDays(7), credentials);
            return _jwtTokenHandler.WriteToken(jwtToken);
        }
    }


}

这是我从控制器调用它的方式:

namespace WebApiDocker.Controllers
{
    [Route("api/health")]
    [ApiController]
    public class HealthController : ControllerBase
    {
        private readonly AppSettings _appSettings;
        private readonly JwtTokenProvider _jwtTokenProvider;

        public HealthController(AppSettings appSettings, JwtTokenProvider jwtTokenProvider)
        {
            this._appSettings = appSettings;
            this._jwtTokenProvider = jwtTokenProvider;
        }

        [HttpGet]
        public IActionResult Get()
        {
            var statusResponse = new StatusResponse
            {
                Status = "Up",
                AppSettings = _appSettings,
                Message = _jwtTokenProvider.GenerateTokenForUser(1)
            };
            return Ok(statusResponse);
        }
    }
}

但是它不起作用,并且我收到以下异常消息:

ArgumentOutOfRangeException: IDX10603: Decryption failed. Keys tried: '[PII is hidden]'. Exceptions caught: '[PII is hidden]'. token: '[PII is hidden]'
 Parameter name: KeySize
Microsoft.IdentityModel.Tokens.SymmetricSignatureProvider..ctor(SecurityKey key, string algorithm, bool willCreateSignatures)
Microsoft.IdentityModel.Tokens.CryptoProviderFactory.CreateSignatureProvider(SecurityKey key, string algorithm, bool willCreateSignatures)
Microsoft.IdentityModel.Tokens.CryptoProviderFactory.CreateForSigning(SecurityKey key, string algorithm)
Microsoft.IdentityModel.JsonWebTokens.JwtTokenUtilities.CreateEncodedSignature(string input, SigningCredentials signingCredentials)
System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.CreateJwtSecurityTokenPrivate(string issuer, string audience, ClaimsIdentity subject, Nullable<DateTime> notBefore, Nullable<DateTime> expires, Nullable<DateTime> issuedAt, SigningCredentials signingCredentials, EncryptingCredentials encryptingCredentials)
System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.CreateToken(SecurityTokenDescriptor tokenDescriptor)
WebApiDocker.Config.Jwt.JwtTokenProvider.GenerateTokenForUser(int userId) in JwtTokenProvider.cs
+
            var token = _jwtTokenHandler.CreateToken(tokenDescriptor);
WebApiDocker.Controllers.HealthController.Get() in HealthController.cs
+
            var statusResponse = new StatusResponse
lambda_method(Closure , object , object[] )
Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(object target, object[] parameters)

1 个答案:

答案 0 :(得分:5)

看起来这是密钥大小的问题,我用key as secret运行了一个很小的示例测试项目。我更改了key to some_big_key_value_here_secret,它的工作方式如@Arsiwaldi

所述