c#

JWT token在C#中的应用

小樊
161
2024-08-30 22:59:22
栏目: 编程语言

JSON Web Token(JWT)是一种开放标准,用于在网络之间安全地传输信息。JWT 可以用来身份验证和授权。在 C# 中,你可以使用 JWT 来保护你的 Web API 或者其他需要安全访问的资源。

以下是在 C# 中使用 JWT 的基本步骤:

  1. 安装 System.IdentityModel.Tokens.Jwt 和 Microsoft.IdentityModel.Tokens 包:
dotnet add package System.IdentityModel.Tokens.Jwt
dotnet add package Microsoft.IdentityModel.Tokens
  1. 创建一个 JWT 令牌:
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 = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your-secret-key"));
            var signinCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var claims = new Claim[]
            {
                new Claim(JwtRegisteredClaimNames.Sub, "user-id"),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(ClaimTypes.Role, "admin")
            };

            var jwtToken = new JwtSecurityToken(
                issuer: "issuer",
                audience: "audience",
                claims: claims,
                expires: DateTime.UtcNow.AddMinutes(30),
                signingCredentials: signinCredentials
            );

            var tokenString = new JwtSecurityTokenHandler().WriteToken(jwtToken);
            Console.WriteLine($"Generated JWT: {tokenString}");
        }
    }
}
  1. 验证 JWT 令牌:
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Text;
using Microsoft.IdentityModel.Tokens;

namespace JwtExample
{
    class Program
    {
        static void Main(string[] args)
        {
            var tokenString = "your-jwt-token";
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your-secret-key"));
            var validationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidIssuer = "issuer",
                ValidateAudience = true,
                ValidAudience = "audience",
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = key
            };

            try
            {
                var jwtTokenHandler = new JwtSecurityTokenHandler();
                var principal = jwtTokenHandler.ValidateToken(tokenString, validationParameters, out _);
                Console.WriteLine($"Token is valid. User ID: {principal.FindFirst(ClaimTypes.NameIdentifier)?.Value}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Token is not valid: {ex.Message}");
            }
        }
    }
}
  1. 在 ASP.NET Core 中使用 JWT 进行身份验证和授权:

首先,安装 Microsoft.AspNetCore.Authentication.JwtBearer 包:

dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer

然后,在 Startup.cs 文件中配置 JWT 身份验证:

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;

namespace JwtExample
{
    public class Startup
    {
        // ...

        public void ConfigureServices(IServiceCollection services)
        {
            // ...

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options =>
                {
                    options.RequireHttpsMetadata = false;
                    options.SaveToken = true;
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuer = true,
                        ValidIssuer = "issuer",
                        ValidateAudience = true,
                        ValidAudience = "audience",
                        ValidateIssuerSigningKey = true,
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your-secret-key"))
                    };
                });

            // ...
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            // ...

            app.UseAuthentication();
            app.UseAuthorization();

            // ...
        }
    }
}

现在,你可以在控制器中使用 [Authorize] 属性来保护需要身份验证的端点:

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace JwtExample.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        [HttpGet]
        [Authorize]
        public string Get()
        {
            return "Hello, authorized user!";
        }
    }
}

这就是在 C# 中使用 JWT 的基本概述。你可以根据自己的需求进行调整和扩展。

0
看了该问题的人还看了