溫馨提示×

c# jwtbuilder有示例代碼嗎

c#
小樊
112
2024-12-12 22:54:06
欄目: 編程語言

當然,我可以為您提供一個使用C#和JWT(JSON Web Token)的示例代碼。以下是一個簡單的示例,演示如何使用System.IdentityModel.Tokens.JwtMicrosoft.IdentityModel.Tokens包來創建和驗證JWT令牌:

首先,確保已安裝以下NuGet包:

  • System.IdentityModel.Tokens.Jwt
  • Microsoft.IdentityModel.Tokens

然后,創建一個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_issueryour_audience替換為您自己的值。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女