【发布时间】:2016-01-13 08:24:41
【问题描述】:
在应用程序重新启动或发布后,我使用有效令牌收到以下错误
IDX10503: Signature validation failed. Keys tried: 'System.IdentityModel.Tokens.RsaSecurityKey
Exceptions caught:
token: '{"typ":"JWT","alg":"RS256","kid":null}.{"unique_name":"test@test.com","iss":"XXXXXX","aud":"XXXXX","exp":1444876186}'
这是生成KEY的函数
private void generateRsaKeys()
{
using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(2048))
{
key = new RsaSecurityKey(rsa.ExportParameters(true));
credentials = new SigningCredentials (key,SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest);
rsa.PersistKeyInCsp = true;
}
}
这样配置就完成了
services.ConfigureOAuthBearerAuthentication(options =>
{
options.AutomaticAuthentication = true;
options.TokenValidationParameters.IssuerSigningKey = generateRsaKeys();
options.TokenValidationParameters.ValidAudience = audience;
options.TokenValidationParameters.ValidIssuer = issuer;
});
app.UseStaticFiles();
app.UseOAuthBearerAuthentication();
// Add MVC to the request pipeline.
app.UseMvc();
这是我控制器上的操作
// POST: /token
[HttpPost()]
public async Task<IActionResult> Token([FromBody] LoginModel model)
{
if (!ModelState.IsValid)
return HttpBadRequest();
JwtSecurityTokenHandler handler = _bearerOptions.SecurityTokenValidators.OfType<JwtSecurityTokenHandler>().First();
try
{
var user = await _Repo.GetDetailAsync(model.Email);
if (!model.Password.Equals(user.Password))
return HttpUnauthorized();
JwtSecurityToken securityToken = handler.CreateToken
(
issuer: _bearerOptions.TokenValidationParameters.ValidIssuer,
audience: _bearerOptions.TokenValidationParameters.ValidAudience,
signingCredentials: _signingCredentials,
subject: new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, user.Email) }),
expires: DateTime.Now.AddMinutes(2)
);
string token = handler.WriteToken(securityToken);
return new ObjectResult(new TokenModel() { AccessToken = token, TokenType = "bearer" });
}
catch (Exception ex)
{
// TODO: add loggin logic here
return HttpUnauthorized();
}
}
【问题讨论】: