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

Posted

技术标签:

【中文标题】C# Jwt 令牌生成失败 asp.net core 2.2【英文标题】:C# Jwt Token generation failed asp.net core 2.2 【发布时间】:2019-06-26 19:05:18 【问题描述】:

我正在尝试为 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)

【问题讨论】:

您的密钥返回多少字节?根据异常,KeySize 有问题。 【参考方案1】:

看起来这是关键尺寸问题,我用key as secret 运行了一个示例测试项目,它很小。我更改了key to some_big_key_value_here_secret,它按照@Arsiwaldi 的通知工作

【讨论】:

一样!我不得不让我的钥匙更大。为了测试目的,我把它弄小了

以上是关于C# Jwt 令牌生成失败 asp.net core 2.2的主要内容,如果未能解决你的问题,请参考以下文章

ASP.NET Core 2.0 JWT 验证失败并出现“用户授权失败:(null)”错误

ASP.NET Core 中的 Jwt 令牌身份验证

使用 JWT 在 c# 中生成令牌的无效签名

单次使用 Jwt Token 在 angular 6 的 asp.net 核心中进行电子邮件验证

我们可以在 Asp.NET Core 中销毁/无效 JWT 令牌吗?

JWT不记名令牌授权不起作用asp net core web api