public HttpResponseMessage Get()
{
var secretKey = Convert.ToBase64String(Encoding.UTF8.GetBytes("MYSECRETKEY"));
var symmetricKey = Convert.FromBase64String(secretKey);
var tokenHandler = new JwtSecurityTokenHandler();
var now = DateTime.UtcNow;
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.Name, "John")
}),
Expires = now.AddMinutes(Convert.ToInt32(5)),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(symmetricKey), SecurityAlgorithms.HmacSha256Signature)
};
var stoken = tokenHandler.CreateToken(tokenDescriptor);
var token = tokenHandler.WriteToken(stoken);
return Request.CreateResponse(HttpStatusCode.OK, token);
}
I'm testing Json Web Token on Asp.Net Web Api but I received error when var stoken = tokenHandler.CreateToken(tokenDescriptor);
is executed, the error message that I received was:
System.ArgumentOutOfRangeException
HResult=0x80131502
Message=IDX10603: Decryption failed. Keys tried: '[PII is hidden]'.
Exceptions caught:
'[PII is hidden]'.
token: '[PII is hidden]'
Parameter name: KeySize
Source=Microsoft.IdentityModel.Tokens
StackTrace:
at Microsoft.IdentityModel.Tokens.SymmetricSignatureProvider..ctor(SecurityKey key, String algorithm, Boolean willCreateSignatures)
at Microsoft.IdentityModel.Tokens.CryptoProviderFactory.CreateSignatureProvider(SecurityKey key, String algorithm, Boolean willCreateSignatures)
at Microsoft.IdentityModel.Tokens.CryptoProviderFactory.CreateForSigning(SecurityKey key, String algorithm)
at Microsoft.IdentityModel.JsonWebTokens.JwtTokenUtilities.CreateEncodedSignature(String input, SigningCredentials signingCredentials)
at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.CreateJwtSecurityTokenPrivate(String issuer, String audience, ClaimsIdentity subject, Nullable`1 notBefore, Nullable`1 expires, Nullable`1 issuedAt, SigningCredentials signingCredentials, EncryptingCredentials encryptingCredentials)
at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.CreateToken(SecurityTokenDescriptor tokenDescriptor)
at Life_Saving_Society_Malaysia.Controllers.LoginController.Get() in C:\Users\Lucas PC\source\repos\Life Saving Society Malaysia\Life Saving Society Malaysia\Controllers\LoginController.cs:line 35
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass6_1.<GetExecutor>b__3(Object instance, Object[] methodParameters)
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)
Also how do you create a Custom AuthorizeFilterAttribute (Authorize using Json Web Token) for Web API? (NOT Asp.Net Core)
User contributions licensed under CC BY-SA 3.0