2017-09-27 19 views
0

我编写代码来生成JWT并在证书上签名,但它在我不想要的标题中添加kid属性。如何创建未使用此属性的证书签名的JWT?这里是我的代码:在标题中创建没有孩子的JWT

public string CreateToken(string thumbprint, string iss, string sub, string aud, int lifetime) 
    { 
     X509Certificate2 cert = null; 

     var certificateStore = new X509Store(StoreName.My, StoreLocation.CurrentUser); 
     var lifeDuration = new Lifetime(DateTime.Now, DateTime.Now.AddMinutes(lifetime)); 
     var tokenHandler = new JwtSecurityTokenHandler(); 

     certificateStore.Open(OpenFlags.ReadOnly); 

     foreach (var certificate in certificateStore.Certificates) 
     { 
      if (certificate == null || certificate.Thumbprint == null) 
      { 
       continue; 
      } 

      if (string.Equals(certificate.Thumbprint, thumbprint, StringComparison.CurrentCultureIgnoreCase)) 
      { 
       certificateStore.Close(); 
       cert = certificate; 
       break; 
      } 
     } 

     if (cert == null) 
     { 
      throw new Exception("Certificate cannot be found!"); 
     } 

     var signingCredentials = new SigningCredentials(new X509SecurityKey(cert), SecurityAlgorithms.RsaSha256Signature); 

     var tokenDescriptor = new Microsoft.IdentityModel.Tokens.SecurityTokenDescriptor 
     { 

      Issuer = iss, 
      Subject = new ClaimsIdentity(new Claim[] 
       { 
        new Claim("sub", sub), 
        new Claim("jti", Guid.NewGuid().ToString()) 
       }), 
      Audience = aud, 
      Expires = lifeDuration.Expires, 
      SigningCredentials = signingCredentials 
     }; 

     Microsoft.IdentityModel.Tokens.SecurityToken token = tokenHandler.CreateToken(tokenDescriptor); 

     string tokenString = tokenHandler.WriteToken(token); 

     return tokenString; 
    } 

以上代码生成此令牌:

{ 
"alg": "RS256", 
"kid": "B8C72D1B7A713A09372F2376094CC525A023379C", 
"typ": "JWT" 
} 
{ 
"jti": "216fcf32-d4ae-4b5a-a255-79733b2e4535", 
"exp": "1506496792", 
"iat": "1506496792", 
"iss": "issuer", 
"aud": "audience", 
"sub": "subject" 
} 

回答

0

我已经改变了我的方法是这样的,现在它工作正常

public string CreateToken(string thumbprint, string iss, string sub, string aud, int lifetime) 
    { 
     var lifeDuration = new Lifetime(DateTime.Now, DateTime.Now.AddMinutes(lifetime)); 
     var cert = this.FindCertificate(thumbprint); 
     var signingCredentials = new SigningCredentials(new X509SecurityKey(cert), SecurityAlgorithms.RsaSha256Signature); 

     JwtHeader header = new JwtHeader(signingCredentials); 
     header.Clear(); 
     header.Add("alg", "RS256"); 
     header.Add("typ", "JWT"); 

     JwtPayload payload = new JwtPayload(
      iss, 
      aud, 
      new List<Claim>() 
      { 
       new Claim("sub", sub), 
       new Claim("jti", Guid.NewGuid().ToString()) 
      }, 
      null, 
      lifeDuration.Expires); 

     var jwt = new JwtSecurityToken(header, payload); 
     var encoded = new JwtSecurityTokenHandler().WriteToken(jwt); 

     return encoded; 
    } 
相关问题