在C#中生成和使用token通常涉及到身份验证和授权
安装System.IdentityModel.Tokens.Jwt和Microsoft.IdentityModel.Tokens包。在.NET项目中,打开NuGet包管理器控制台并运行以下命令:Install-Package System.IdentityModel.Tokens.JwtInstall-Package Microsoft.IdentityModel.Tokens创建一个方法来生成token。首先,需要创建一个RSA(非对称加密)密钥对。可以使用以下代码生成密钥对并将其保存为XML字符串:using System.Security.Cryptography;private static string GenerateKeyPair(){ using (var rsa = new RSACryptoServiceProvider(2048)) { return rsa.ToXmlString(true); }}使用以下代码生成token: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);}验证和解析token: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;}在你的应用程序中使用这些方法。例如,在ASP.NET Core Web API中,可以在登录方法中生成token,并在需要身份验证的API方法中验证token。生成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}注意:在实际应用中,不要在内存中存储密钥对,而是将其安全地存储在配置文件或环境变量中。此外,确保在生产环境中使用更长的过期时间。


