2017-07-19 129 views
1

我正在使用VS 2017和.NET 4.6.2開發C#Web Api MVC項目,我想用我的證書籤署JSON Web令牌C#不能使用證書籤名JWT

這是我的代碼:

using SolutionDOC_Common; 
using SolutionDOC_Interface.Repository.Authentication; 
using SolutionDOC_SDK.Model; 
using System; 
using System.Collections.Generic; 
using System.Configuration; 
using System.IdentityModel.Tokens.Jwt; 
using System.Security.Authentication; 
using System.Security.Claims; 
using System.Security.Cryptography; 
using System.Security.Cryptography.X509Certificates; 
using mit = Microsoft.IdentityModel.Tokens; 

public string Build(Credentials credentials) 
{ 
    string thumbprint = ConfigurationManager.AppSettings["CertificateThumbprint"]; 
    string tokenIssuer = ConfigurationManager.AppSettings["TokenIssuer"]; 
    string tokenAudience = ConfigurationManager.AppSettings["TokenAudience"]; 

    List<Claim> claims = new List<Claim> 
    { 
     new Claim(ClaimTypes.Name, credentials.Username), 
     new Claim(ClaimTypes.Surname, credentials.Alias) 
    }; 

    X509Certificate2 cert = CertificateUtility.GetCertificateByThumbprint(thumbprint); 
    RSACryptoServiceProvider publicAndPrivate = (RSACryptoServiceProvider)cert.PublicKey.Key; 

    JwtSecurityToken jwtToken = new JwtSecurityToken 
    (
     issuer: tokenIssuer, 
     audience: tokenAudience, 
     claims: claims, 
     signingCredentials: new mit.SigningCredentials(new mit.RsaSecurityKey(publicAndPrivate), mit.SecurityAlgorithms.RsaSha256Signature), 
     expires: DateTime.Now.AddDays(30) 
    ); 

    JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler(); 

    // This throws the InvalidOperationException! 
    string tokenString = tokenHandler.WriteToken(jwtToken); 

    return tokenString; 

    throw new AuthenticationException(); 
} 

tokenHandler.WriteToken(jwtToken)線,拋出一個InvalidOperationException

「IDX10638:無法創建SignatureProvider, 'key.HasPrivateKey' 是假的,不能創建簽名。鍵:Microsoft.IdentityModel.Tokens.RsaSecurityKey。'

相應證書的權限設置爲IIS_IUSRS用戶,因此它也可以讀取私鑰。該證書實際上是一個使用IIS生成的自簽名證書,該證書具有私鑰。 拇指指紋設置正確,所以我得到正確的證書。 所以我正確地得到了X509Certificate2對象。 X509Certificate2對象的PrivateKey屬性已填充。

它爲什麼不起作用?

回答

1

那麼,即使您標記了變量publicAndPrivate,您顯然只能提取公鑰。試試

RSACryptoServiceProvider publicAndPrivate = (RSACryptoServiceProvider)cert.PrivateKey;