【问题标题】:Creating Web Token issue创建 Web 令牌问题
【发布时间】: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'。'


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

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

    }

【问题讨论】:

  • 我有一个存储库,例如 JWT 身份验证,检查它是StartupAccountControllergithub.com/lugrugzo/WebApiJwt
  • 非常感谢西尔万!很有帮助。

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


【解决方案1】:

我被困在同一个地方(作者的道具或这个howto -> ASP.NET Core 2.0 Bearer Authentication。关键长度是问题,可能是作者的错字。

代替;

JwtSecurityKey.Create("fiversecret ")

使用

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

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

    • 谢谢。不确定我需要对代码进行哪些更改?我对 JWT 很陌生。你是说我应该:用随机的 32 个字符的文本字符串替换下面的原始代码中的“fiversecret”文本? .AddSecurityKey(JwtSecurityKey.Create("fiversecret "))
    猜你喜欢
    • 1970-01-01
    • 2019-01-12
    • 2018-04-07
    • 2019-02-26
    • 1970-01-01
    • 2013-11-28
    • 1970-01-01
    • 2015-04-12
    • 2011-10-22
    相关资源
    最近更新 更多