创建Web令牌问题

时间:2017-11-01 05:10:23

标签: asp.net-core jwt asp.net-core-2.0

我正在尝试在.Net Core 2 web api应用程序中创建和使用JWT进行授权。此行在下面以粗体显示错误:

public string Value => new JwtSecurityTokenHandler().WriteToken(this.token);
  

System.ArgumentOutOfRangeException:' IDX10603:算法:' HS256'   要求SecurityKey.KeySize大于' 128'位。   KeySize报道:' 96'。'

以下是完整的代码。来源来自:

https://github.com/TahirNaushad/Fiver.Security.Bearer/blob/master/Fiver.Security.Bearer.Helpers/JwtToken.cs

    [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");
        }

    }

2 个答案:

答案 0 :(得分:1)

  

块大小:数据块的大小是底层哈希算法   经营。对于SHA-256,这是512位,对于SHA-384和SHA-512,   这是1024位。

     

输出长度:底层产生的哈希值的大小   哈希算法。对于SHA-256,这是256位,对于SHA-384,这是384   位,对于SHA-512,这是512位。

因此我们需要128位密钥。如果要将其存储为文本,则可以通过生成随机 32个字符长度字符串来表示128位密钥。

答案 1 :(得分:1)

我被卷入了同一个地方(道具给作者或者这个howto - &gt; ASP.NET Core 2.0 Bearer Authentication。关键长度是问题,可能是作者部分的错字。

而不是;

JwtSecurityKey.Create("fiversecret ")

使用

JwtSecurityKey.Create("fiver-secret-key")