私は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プロパティが設定されます。
なぜ機能しないのですか?