2017-07-19 4 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; 
関連する問題