在C#中生成和使用token通常涉及到身份驗證和授權
Install-Package System.IdentityModel.Tokens.Jwt
Install-Package Microsoft.IdentityModel.Tokens
using System.Security.Cryptography;
private static string GenerateKeyPair()
{
using (var rsa = new RSACryptoServiceProvider(2048))
{
return rsa.ToXmlString(true);
}
}
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using Microsoft.IdentityModel.Tokens;
public static string GenerateToken(string keyPair, string issuer, string audience, int expirationMinutes)
{
var securityKey = new RsaSecurityKey(new RSACryptoServiceProvider().FromXmlString(keyPair));
var signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.RsaSha256Signature);
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, "your_subject"),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
};
var jwt = new JwtSecurityToken(
issuer: issuer,
audience: audience,
claims: claims,
notBefore: DateTime.UtcNow,
expires: DateTime.UtcNow.AddMinutes(expirationMinutes),
signingCredentials: signingCredentials);
return new JwtSecurityTokenHandler().WriteToken(jwt);
}
public static ClaimsPrincipal ValidateToken(string token, string keyPair, string issuer, string audience)
{
var validationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = issuer,
ValidateAudience = true,
ValidAudience = audience,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new RsaSecurityKey(new RSACryptoServiceProvider().FromXmlString(keyPair))
};
var jwtSecurityTokenHandler = new JwtSecurityTokenHandler();
var principal = jwtSecurityTokenHandler.ValidateToken(token, validationParameters, out _);
return principal;
}
生成token:
var keyPair = GenerateKeyPair();
var token = GenerateToken(keyPair, "issuer", "audience", 60);
驗證token:
var principal = ValidateToken(token, keyPair, "issuer", "audience");
if (principal != null)
{
// Token is valid, proceed with the authorized operation
}
else
{
// Token is invalid, deny access
}
注意:在實際應用中,不要在內存中存儲密鑰對,而是將其安全地存儲在配置文件或環境變量中。此外,確保在生產環境中使用更長的過期時間。