无法从JwtSecurityToken获得签名

时间:2016-03-21 20:06:03

标签: c# .net oauth jwt

我试图在.NET中使用JWT身份验证,我需要将结果看起来像这样:

部首:  {"alg":"HS512"}

有效负载:

{"sub":"SomeSubject","nbf":1458315105,"exp":1458316305,"iat":1458315705}

我编写了以下代码来获取JWT签名令牌:

 public async Task<string> GetJWTToken(string user)
        {
            var now = DateTime.UtcNow;

            JwtHeader jwtHeader = new JwtHeader();

            jwtHeader.Add("alg", JwtAlgorithms.HMAC_SHA512);

            JwtPayload payload = new JwtPayload();
            payload.Add("sub", user);
            payload.Add("exp", ConvertToUnixTimestamp( now.AddMinutes(10)));
            payload.Add("nbf",ConvertToUnixTimestamp(now.AddMinutes(-10)));
            payload.Add("iat",ConvertToUnixTimestamp(now));

            JwtSecurityToken toekn = new JwtSecurityToken(jwtHeader, payload);
            SigningCredentials cred = new SigningCredentials(new InMemorySymmetricSecurityKey(Encoding.UTF8.GetBytes("SomeKey")), "http://www.w3.org/2001/04/xmldsig-more#hmac-sha512", "http://www.w3.org/2001/04/xmlenc#sha512");

            //what's next? 
            return finalResult;
          }

使用此代码我只能加密Header和Payload,我没有签名。我查看了很多地方,但无法找到产生类似有效载荷和标题的示例。

1-如何将签名凭证添加到toeken;无法设置SigningCredentials,SigningToken和SigningKeys。不确定签名凭据应该适合的位置。

2-之后,Signature是如何制作的?

1 个答案:

答案 0 :(得分:1)

以下代码显示了如何创建JWT令牌,其中“证书”可以是自签名证书。

    public JwtTokenProvider(string authority)
    {
        _authority = authority;
    }
    public async Task<TokenResult> GetTokenAsync(string clientId, string resource)
    {
        return await Task.FromResult(new TokenResult
        {
            AccessTokenType = "Bearer",
            IdToken = CreateJwt(clientId, resource)
        });
    }
    private string CreateJwt(string clientId, string resource)
    {
        var certificate = new X509Certificate2(Resource.notification, CertPassword);
        var sub = new System.Security.Claims.Claim("sub", clientId);
        var jti = new System.Security.Claims.Claim("jti", Guid.NewGuid().ToString());
        var claims = new List<System.Security.Claims.Claim>() { sub, jti };
        var x509Key = new X509AsymmetricSecurityKey(certificate);
        var signingCredentials = new SigningCredentials(x509Key, SecurityAlgorithms.RsaSha256Signature,
            SecurityAlgorithms.Sha256Digest);
        var jwt = new JwtSecurityToken(_authority, resource, claims,
            DateTime.UtcNow,
            DateTime.UtcNow.AddMinutes(ExpirationInMinutes), signingCredentials);
        var sign = new SignatureProviderFactory();
        var provider = sign.CreateForSigning(x509Key, SecurityAlgorithms.RsaSha256Signature);
        var input = string.Join(".", new[] { jwt.EncodedHeader, jwt.EncodedPayload });
        var signed = provider.Sign(Encoding.UTF8.GetBytes(input));
        sign.ReleaseProvider(provider);
        return string.Join(".", new[] { jwt.EncodedHeader, jwt.EncodedPayload, Base64UrlEncoder.Encode(signed) });
    }