在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
}
注意:在实际应用中,不要在内存中存储密钥对,而是将其安全地存储在配置文件或环境变量中。此外,确保在生产环境中使用更长的过期时间。