.Net Core webapi 实现JWT认证

文章目录

    • 需求
    • 准备
    • 创建JWT配置
    • 创建JWTService
    • 注册JWT
    • 创建中间件读取jwt的token
    • 在需要的接口上添加属性
    • 启动认证
    • 启动swagger的授权认证
    • 使用

需求

实现一个记录某个用户所有操作的功能

准备

  1. 创建你的webapi项目
  2. 从nuget下载安装JWT资源包根据你的项目使用.net版本下载对应的jwt版本,测试项目使用了.net8.0:
    Microsoft.AspNetCore.Authentication.JwtBearer
    .Net Core webapi 实现JWT认证_第1张图片

创建JWT配置

在appsettings.json中新增JWTOptions

"JWTOptions": {
   
  //你的jwt加密密钥
  "SecretKey": "ThisIsASecretKeyForJWTTokenGeneration",
  "Issuer": "localhost", //令牌颁发者
  "Audience": "localhost", //令牌接收者
  "Expired": 5 //令牌过期时间
}

创建jwt配置类并注册

public class JWTOptions
{
    /// 
    /// jwt加密密钥,任意字符串
    /// 
    public string SecretKey { get; set; }

    /// 
    /// 颁发者
    /// 
    public string Issuer { get; set; }

    /// 
    /// 接收者
    /// 
    public string Audience { get; set; }

    /// 
    /// 过期时间
    /// 
    public int Expired { get; set; }
}

//在program.cs中注册该option
builder.Services.Configure(builder.Configuration.GetSection("JWTOptions"));

创建JWTService

创建服务生成token

public class GenerateJWTService
{

    private readonly JWTOptions _options;

    public GenerateJWTService(IOptionsMonitor options)
    {
        _options = options.CurrentValue;
    }

    public JWTokenTResult GenerateToken(string userName)
    {
        var claims = new List 
        {
            new("userName", userName),
            new(JwtRegisteredClaimNames.Sub, userName),
        };

        var validFrom = DateTime.Now;
        var validTo = DateTime.Now.AddMinutes(10);
        //创建令牌
        var jwt = new JwtSecurityToken(
            issuer: _options.Issuer,
            audience: _options.Audience,
            claims: claims,
            notBefore: validFrom,
            expires: validTo,
            signingCredentials: new Microsoft.IdentityModel.Tokens.SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_options.Secr

你可能感兴趣的:(.netcore,JWT授权)