當然,我可以為您提供一個使用C#和JWT(JSON Web Token)的示例代碼。以下是一個簡單的示例,演示如何使用System.IdentityModel.Tokens.Jwt
和Microsoft.IdentityModel.Tokens
包來創建和驗證JWT令牌:
首先,確保已安裝以下NuGet包:
然后,創建一個C#控制臺應用程序并添加以下代碼:
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.IdentityModel.Tokens;
namespace JwtExample
{
class Program
{
static void Main(string[] args)
{
// 定義密鑰和簽名算法
var key = Encoding.UTF8.GetBytes("your_secret_key");
var signingCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256);
// 創建JWT載荷
var claims = new[]
{
new Claim(ClaimTypes.Name, "John Doe"),
new Claim(ClaimTypes.Email, "john.doe@example.com")
};
// 創建JWT令牌
var jwtToken = new JwtSecurityToken(
issuer: "your_issuer",
audience: "your_audience",
claims: claims,
expires: DateTime.UtcNow.AddMinutes(30),
signingCredentials: signingCredentials
);
// 序列化JWT令牌為字符串
var jwtTokenString = new JwtSecurityTokenHandler().WriteToken(jwtToken);
Console.WriteLine("JWT Token: " + jwtTokenString);
// 驗證JWT令牌
var validationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = "your_issuer",
ValidateAudience = true,
ValidAudience = "your_audience",
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero
};
try
{
var principal = new JwtSecurityTokenHandler().ValidateToken(jwtTokenString, validationParameters, out SecurityToken validatedToken);
Console.WriteLine("Token validated successfully. Principal: " + principal.Identity.Name);
}
catch (Exception ex)
{
Console.WriteLine("Error validating token: " + ex.Message);
}
}
}
}
在這個示例中,我們首先定義了一個密鑰和簽名算法,然后創建了一個包含用戶名和電子郵件的JWT載荷。接下來,我們使用這些信息創建了一個JWT令牌,并將其序列化為字符串。最后,我們驗證了JWT令牌的有效性,并在成功驗證后輸出了令牌的主體名稱。
請注意,您需要將your_secret_key
、your_issuer
和your_audience
替換為您自己的值。