JSON Web Token(JWT)是一种用于在网络间传递声明的开放标准(RFC 7519),常用于对身份验证和授权信息进行安全传递。在.NET中,你可以使用一些库来轻松地创建和验证JWT。以下是一个简单的示例,演示如何在.NET中使用JWT:
首先,你需要安装.NET中的JWT库。常见的选择包括System.IdentityModel.Tokens.Jwt。
通过NuGet包管理器控制台安装库:
- Install-Package System.IdentityModel.Tokens.Jwt
-
下面是一个使用C#生成JWT的示例:
- using System;
- using System.IdentityModel.Tokens.Jwt;
- using System.Security.Claims;
- using Microsoft.IdentityModel.Tokens;
-
- class Program
- {
- static void Main(string[] args)
- {
- var securityKey = new SymmetricSecurityKey(Convert.FromBase64String("your-secret-key"));
- var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
-
- var claims = new[]
- {
- new Claim(JwtRegisteredClaimNames.Sub, "your-username"),
- new Claim(JwtRegisteredClaimNames.Email, "your-email@example.com"),
- new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
- };
-
- var token = new JwtSecurityToken(
- issuer: "your-issuer",
- audience: "your-audience",
- claims: claims,
- expires: DateTime.Now.AddHours(1),
- signingCredentials: credentials
- );
-
- var encodedToken = new JwtSecurityTokenHandler().WriteToken(token);
- Console.WriteLine(encodedToken);
- }
- }
-
请确保替换上述代码中的密钥、用户名、电子邮件、发行者和受众等信息。
下面是一个使用C#验证JWT的示例:
- using Microsoft.IdentityModel.Tokens;
-
- class Program
- {
- static void Main(string[] args)
- {
- var tokenHandler = new JwtSecurityTokenHandler();
- var token = "your-jwt-token";
-
- var validationParameters = new TokenValidationParameters
- {
- ValidateIssuerSigningKey = true,
- IssuerSigningKey = new SymmetricSecurityKey(Convert.FromBase64String("your-secret-key")),
- ValidateIssuer = true,
- ValidIssuer = "your-issuer",
- ValidateAudience = true,
- ValidAudience = "your-audience",
- ValidateLifetime = true,
- ClockSkew = TimeSpan.Zero // Optional: Adjust clock skew if needed
- };
-
- SecurityToken validatedToken;
- var principal = tokenHandler.ValidateToken(token, validationParameters, out validatedToken);
- Console.WriteLine("Token is valid.");
- }
- }
-
替换代码中的JWT令牌、密钥、发行者和受众等信息。
这个示例是一个简单的入门,实际应用中可能还需要更复杂的配置和逻辑。JWT还支持更多的声明和配置选项,以满足各种身份验证和授权需求。