【发布时间】:2018-04-13 09:37:38
【问题描述】:
我正在尝试在 .Net Core 2 Web api 应用程序中创建和使用 JWT 进行授权。此行产生以下粗体错误:
public string Value => new JwtSecurityTokenHandler().WriteToken(this.token);
System.ArgumentOutOfRangeException:'IDX10603:算法:'HS256' 要求 SecurityKey.KeySize 大于“128”位。 KeySize 报告:'96'。'
下面是完整的代码。来源来自:
[AllowAnonymous]
[HttpPost, Route("CreateToken")]
public IActionResult CreateToken([FromBody]RegisterMemberModel inputModel)
{
var token = new JwtTokenBuilder()
.AddSecurityKey(JwtSecurityKey.Create("fiversecret "))
.AddSubject("james bond")
.AddIssuer("Fiver.Security.Bearer")
.AddAudience("Fiver.Security.Bearer")
.AddClaim("MembershipId", "111")
.AddExpiry(1)
.Build();
return Ok(token.Value);
}
public sealed class JwtToken
{
private JwtSecurityToken token;
internal JwtToken(JwtSecurityToken token)
{
this.token = token;
}
public DateTime ValidTo => token.ValidTo;
public string Value => new JwtSecurityTokenHandler().WriteToken(this.token);
}
public sealed class JwtTokenBuilder
{
private SecurityKey securityKey = null;
private string subject = "";
private string issuer = "";
private string audience = "";
private Dictionary<string, string> claims = new Dictionary<string, string>();
private int expiryInMinutes = 5;
public JwtTokenBuilder AddSecurityKey(SecurityKey securityKey)
{
this.securityKey = securityKey;
return this;
}
public JwtTokenBuilder AddSubject(string subject)
{
this.subject = subject;
return this;
}
public JwtTokenBuilder AddIssuer(string issuer)
{
this.issuer = issuer;
return this;
}
public JwtTokenBuilder AddAudience(string audience)
{
this.audience = audience;
return this;
}
public JwtTokenBuilder AddClaim(string type, string value)
{
this.claims.Add(type, value);
return this;
}
public JwtTokenBuilder AddClaims(Dictionary<string, string> claims)
{
this.claims.Union(claims);
return this;
}
public JwtTokenBuilder AddExpiry(int expiryInMinutes)
{
this.expiryInMinutes = expiryInMinutes;
return this;
}
public JwtToken Build()
{
EnsureArguments();
var claims = new List<Claim>
{
new Claim(JwtRegisteredClaimNames.Sub, this.subject),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
}
.Union(this.claims.Select(item => new Claim(item.Key, item.Value)));
var token = new JwtSecurityToken(
issuer: this.issuer,
audience: this.audience,
claims: claims,
expires: DateTime.UtcNow.AddMinutes(expiryInMinutes),
signingCredentials: new SigningCredentials(
this.securityKey,
SecurityAlgorithms.HmacSha256));
return new JwtToken(token);
}
private void EnsureArguments()
{
if (this.securityKey == null)
throw new ArgumentNullException("Security Key");
if (string.IsNullOrEmpty(this.subject))
throw new ArgumentNullException("Subject");
if (string.IsNullOrEmpty(this.issuer))
throw new ArgumentNullException("Issuer");
if (string.IsNullOrEmpty(this.audience))
throw new ArgumentNullException("Audience");
}
}
【问题讨论】:
-
我有一个存储库,例如 JWT 身份验证,检查它是
Startup和AccountController。 github.com/lugrugzo/WebApiJwt -
非常感谢西尔万!很有帮助。
标签: asp.net-core jwt asp.net-core-2.0