JWT
依赖包:
System.IdentityModel.Tokens.Jwt
Code:
public class JwtModel
{
public string PublicKey { get; set; }
public string PrivateKey { get; set; }
}
private static readonly string _issuer = "issuer";
private static readonly string _audience = "test";
private static readonly string _claimKey = "userId";
private static readonly string _claimValue = "5435";
public static JwtModel GenerateKey()
{
var key = CngKey.Create(CngAlgorithm.ECDsaP256, null, new CngKeyCreationParameters
{
ExportPolicy = CngExportPolicies.AllowPlaintextExport,
});
return new JwtModel
{
PublicKey = Convert.ToBase64String(key.Export(CngKeyBlobFormat.EccPublicBlob)),
PrivateKey = Convert.ToBase64String(key.Export(CngKeyBlobFormat.EccPrivateBlob))
};
}
public static string GenerateToken(string privateKey)
{
var claims = new[]
{
new Claim(_claimKey, _claimValue),
new Claim(JwtRegisteredClaimNames.Sub, "3"),
new Claim(JwtRegisteredClaimNames.Jti, Convert.ToBase64String(Guid.NewGuid().ToByteArray())),
};
var key = CngKey.Import(Convert.FromBase64String(privateKey), CngKeyBlobFormat.EccPrivateBlob);
var cred = new SigningCredentials(
new ECDsaSecurityKey(new ECDsaCng(key)),
SecurityAlgorithms.EcdsaSha256);
var token = new JwtSecurityToken(
issuer: _issuer,
audience: _audience,
claims: claims,
notBefore: DateTime.UtcNow,
expires: DateTime.UtcNow.AddYears(15), //用过 20,18 都不行,还没定位为什么。
signingCredentials: cred);
return new JwtSecurityTokenHandler().WriteToken(token);
}
public static bool VerifyToken(string token, string publicKey)
{
var key = CngKey.Import(
Convert.FromBase64String(publicKey), CngKeyBlobFormat.EccPublicBlob);
SecurityToken validatedToken;
var claims = new JwtSecurityTokenHandler().ValidateToken(
token,
new TokenValidationParameters
{
IssuerSigningKey = new ECDsaSecurityKey(new ECDsaCng(key)),
ValidAudience = _audience,
ValidIssuer = _issuer
},
out validatedToken);
return claims.HasClaim(_claimKey, _claimValue);
}

浙公网安备 33010602011771号