.NET Core 6.0 WebAPI JWT权限验证

无尽追寻 2024-03-05 ⋅ 35 阅读

JWT

简介

在现代的 Web 应用程序中,身份验证和权限验证是非常重要的一部分。Token-Based 带来了很多方便和灵活性,其中 JWT (JSON Web Token) 是一个流行的标准。本文将介绍如何使用 .NET Core 6.0 WebAPI 结合 JWT 实现权限验证的步骤和最佳实践。

1. 安装所需组件

2. 创建.NET Core 6.0 WebAPI 项目

打开命令行或者 Visual Studio 开发人员命令提示符,运行以下命令创建项目:

dotnet new webapi -n MyWebApi
cd MyWebApi

3. 添加 JWT 支持

首先,打开 Startup.cs 文件,在 ConfigureServices 方法中添加以下代码以配置 JWT 认证:

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

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options =>
        {
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidateAudience = true,
                ValidateLifetime = true,
                ValidateIssuerSigningKey = true,
                ValidIssuer = "your_issuer",
                ValidAudience = "your_audience",
                IssuerSigningKey = new SymmetricSecurityKey(
                    Encoding.UTF8.GetBytes("your_secret_key")
                )
            };
        });
    
    services.AddAuthorization();
    
    // ...其他服务的配置
}

请注意,上述代码中的 your_issueryour_audienceyour_secret_key 分别需要替换为你自己的值。

4. 配置身份验证和授权中间件

继续在 Configure 方法中添加以下代码来启用身份验证和授权中间件:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // ...其他配置代码
    
    app.UseRouting();
    
    app.UseAuthentication();
    app.UseAuthorization();
    
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

5. 添加身份验证和授权特性

现在,我们可以在需要进行权限验证的控制器或方法上添加 [Authorize] 特性。例如:

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

[Authorize]
public class UsersController : ControllerBase
{
    // ...
}

6. 发放和验证 JWT

为了发放 JWT,你需要创建一个 Token,并将其加入到 AuthenticationProperties 中。例如,在登录控制器中:

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

[AllowAnonymous]
[HttpPost("login")]
public IActionResult Login([FromBody] LoginModel model)
{
    // 验证用户名和密码
    if (IsValidUser(model.Username, model.Password))
    {
        var token = GenerateToken(model.Username);
        
        return Ok(new { Token = token });
    }
    
    return Unauthorized();
}

private bool IsValidUser(string username, string password)
{
    // 用户名和密码验证逻辑
}

private string GenerateToken(string username)
{
    var claims = new[]
    {
        new Claim(ClaimTypes.Name, username),
        // 可以根据需要添加其他声明
    };
    
    var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your_secret_key"));
    var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
    
    var token = new JwtSecurityToken(
        issuer: "your_issuer",
        audience: "your_audience",
        claims: claims,
        expires: DateTime.Now.AddMinutes(30),
        signingCredentials: credentials
    );
    
    return new JwtSecurityTokenHandler().WriteToken(token);
}

结论

通过使用 .NET Core 6.0 WebAPI 和 JWT,在你的应用程序中实现权限验证变得非常简单。JWT 提供了一种安全的方式来管理身份验证和授权,并具有灵活性和跨平台的优势。请确保在生产环境中妥善保护你的密钥和 JWT。

希望本文能帮助你理解如何在 .NET Core 6.0 WebAPI 中实现 JWT 权限验证。欢迎留言和交流!


全部评论: 0

    我有话说: