問題

私は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)
 

  ベストアンサー

それはキーサイズの問題のように見えます、私は小さいkey as secretでサンプルテストプロジェクトを実行しました。私はkey to some_big_key_value_here_secretを変更し、@ Arsiwaldiによって通知されました

  同じタグがついた質問を見る

c#authenticationjwt