C# .net core web应用 - 配置JWT

在C# .NET Core Web应用中配置JWT(JSON Web Token)可以实现安全的身份验证和授权机制。通常涉及以下几个步骤:

安装必要的NuGet包

确保项目中安装了以下NuGet包:

  • Microsoft.AspNetCore.Authentication.JwtBearer
  • Microsoft.IdentityModel.Tokens

可以通过NuGet包管理器或命令行安装:

dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
dotnet add package Microsoft.IdentityModel.Tokens

配置 JWT 参数(appsettings.json)

在 appsettings.json 中添加 JWT 配置:

{
  "Jwt": {
    "Key": "YourSuperSecretKeyHere_至少16位", // 密钥(推荐使用至少16位)
    "Issuer": "https://yourdomain.com",      // 签发者
    "Audience": "https://yourdomain.com",    // 接收者
    "ExpireMinutes": 60  // 过期时间(分钟)
  }
}

配置JWT认证

program.cs文件中配置JWT认证:

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

var builder = WebApplication.CreateBuilder(args);

// 添加 JWT 认证 两种写法
//builder.Services.AddAuthentication(options =>
//{
    //options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    //定义在 认证(Authentication) 时默认使用的方案(例如解析 JWT Token)。
    //options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    //定义在 质询(Challenge) 时默认使用的方案(例如返回 401 Unauthorized 或跳转到登录页)。
    //options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; 
    //当未显式指定认证方案时,系统默认使用的认证方案。
//})

//简化写法是仅设置 DefaultScheme,其他两个关键属性(Authenticate 和 Challenge)未配置。
//实际使用时返回为null
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = true,            // 验证签发者
        ValidateAudience = true,          // 验证接收者
        ValidateLifetime = true,          // 验证过期时间
        ValidateIssuerSigningKey = true,  // 验证签名密钥
        ValidIssuer = builder.Configuration["Jwt:Issuer"],
        ValidAudience = builder.Configuration["Jwt:Audience"],
        IssuerSigningKey = new SymmetricSecurityKey(
            Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]!)
        )
    };
});
builder.Services.AddAuthorization(); // 添加授权中间件
var app = builder.Build();
app.UseAuthentication(); // 启用认证
app.UseAuthorization();  // 启用授权

app.MapControllers();
app.Run();

AddJwtBearer 类解释

经过上述配置 JWT 已经基本注册在服务中了,接下来是在控制器controller中生成具体的token 用于用户的访问鉴权

生成JWT Token

在控制器或服务中生成JWT Token。包括以下步骤:

// Services/JwtService.cs
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.IdentityModel.Tokens;
public class JwtService
{
    private readonly IConfiguration _config;

    public JwtService(IConfiguration config)
    {
        _config = config;
    }

    public string GenerateToken(string username, string role)
    {
        //1. 生成 JWT 时添加标准声明 JwtRegisteredClaimNames 类规定的字段有很多 感兴趣的见代码下方的link
        var claims = new[]
        {
           new Claim(JwtRegisteredClaimNames.Sub, "user123"),
           new Claim(JwtRegisteredClaimNames.Iss, "https://your-auth-server.com"),
           new Claim(JwtRegisteredClaimNames.Aud, "https://your-api.com"),
           new Claim(JwtRegisteredClaimNames.Exp, DateTimeOffset.UtcNow.AddHours(1).ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64),
           new Claim(JwtRegisteredClaimNames.Iat, DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64),
           new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
           // 自定义声明(非标准)
           new Claim("role", "admin")
        };
        //2. 获取之前配置的 JWT Key
        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]!));
       //3. 指定签名算法和密钥, 配置签名凭证(Signing Credentials)
        var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
        //4. 生成 JWT Token 组合头部(Header)、载荷(Payload)和签名(Signature)。
        var token = new JwtSecurityToken(
            issuer: _config["Jwt:Issuer"],
            audience: _config["Jwt:Audience"],
            claims: claims,
            expires: DateTime.Now.AddMinutes(Convert.ToDouble(_config["Jwt:ExpireMinutes"])),
            signingCredentials: creds
        );

        return new JwtSecurityTokenHandler().WriteToken(token);
    }
}

JwtRegisteredClaimNames 类

保护API端点

使用[Authorize]属性保护需要认证的API端点:

[Authorize]
[HttpGet("protected")]
public IActionResult Protected()
{
    return Ok("This is a protected endpoint.");
}

创建登录接口(生成 Token)


// Controllers/AuthController.cs
using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/auth")]
public class AuthController : ControllerBase
{
    private readonly JwtService _jwtService;

    public AuthController(JwtService jwtService)
    {
        _jwtService = jwtService;
    }

    [HttpPost("login")]
    public IActionResult Login([FromBody] LoginRequest request)
    {
        // 模拟用户验证(实际应查询数据库)
        if (request.Username == "admin" && request.Password == "123456")
        {
            var token = _jwtService.GenerateToken(request.Username, "Admin");
            return Ok(new { Token = token });
        }

        return Unauthorized("用户名或密码错误");
    }
}
public class LoginRequest
{
    public string Username { get; set; }
    public string Password { get; set; }
}

通过以上步骤,可以在C# .NET Core Web应用中成功配置和使用JWT进行认证和授权。
整体来说还是比较复杂的,里面的可扩展性很强,但是实际使用的配置并不是很多,基本也就是流程化的操作。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

何之柱

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值