Jwt 鉴权

[删除(380066935@qq.com或微信通知)]

更好的阅读体验请查看原文:https://www.cnblogs.com/wosperry/p/net6_jwt.html

基本:生成一个 Token


// 以下信息需要与鉴权的地方一致
var key = "1234567890123456";

Claim[] claims = new[] { new Claim("user", username) };

var keyBytes = Encoding.UTF8.GetBytes(key);
var creds = new SigningCredentials( new SymmetricSecurityKey(keyBytes),
                                    SecurityAlgorithms.HmacSha256 );

var jwtSecurityToken = new JwtSecurityToken(
    issuer: "wosperry.com",
    audience: "wosperry.com",
    claims: claims,
    expires: DateTime.Now.AddMinutes(5), // 五分钟后过期
    signingCredentials: creds );

var token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);

封装部分信息到配置文件

  1. 定义 Options 类
public class TokenOptions
{
    public string SecretKey { get; set; }
    public string Issuer { get; set; }
    public string Audience { get; set; }
    public int ExpireMinutes { get; set; } = 30;
}
  1. 在 appsettings.json 添加相关的配置
{
  "TokenOptions": {
    "SecretKey": "123456789456789456",
    "Issuer": "wosperry.com",
    "Audience": "wosperry.com",
    "ExpireMinutes": 2
  }
}
  1. 封装服务
// 接口
public interface IJwtService
{
    Task<string> CreateTokenAsync(string username);
}
// 实现
public class JwtService : IJwtService
{
    public TokenOptions TokenOptions { get; }

    public JwtService(IOptions<TokenOptions> options)
    {
        TokenOptions = options.Value;
    }

    public Task<string> CreateTokenAsync(string username)
    {
        // 添加一些需要的键值对
        Claim[] claims = new[] { new Claim("user", username) };

        var keyBytes = Encoding.UTF8.GetBytes(key);
        var creds = new SigningCredentials( new SymmetricSecurityKey(keyBytes),
                                        SecurityAlgorithms.HmacSha256 );

        var jwtSecurityToken = new JwtSecurityToken(
            issuer: TokenOptions.Issuer,// 签发者
            audience: TokenOptions.Audience,// 接收者
            claims: claims,// payload
            expires: DateTime.Now.AddMinutes(TokenOptions.ExpireMinutes),// 过期时间
            signingCredentials: creds);// 令牌

        var token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
        return Task.FromResult(token);
    }
}
  1. 入口配置
var section = builder.Configuration.GetSection("TokenOptions"); // 获取TokenOptions配置
var tokenOptions = section.Get<TokenOptions>();

builder.Services.AddTransient<IJwtService, JwtService>(); // 注册Jwt服务到容器
builder.Services.Configure<TokenOptions>(section); // 注入IOptions需要这个
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options =>
                {
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuer = true,//是否在令牌期间验证签发者
                        ValidateAudience = true,//是否验证接收者
                        ValidateLifetime = true,//是否验证失效时间
                        ValidateIssuerSigningKey = true,//是否验证签名
                        ValidAudience = tokenOptions.Audience,//接收者
                        ValidIssuer = tokenOptions.Issuer,//签发者,签发的Token的人
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenOptions.SecretKey))
                    };
                });

  1. 请求管道配置( 注意顺序 !!! 
// 注意顺序,不然 401
app.UseAuthentication();
app.UseAuthorization();

  1. 方便 swagger 设置 Header
builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new() { Title = "Perry测试用", Version = "v1", Description = "Perry测试用\r\nPerry测试用\r\nPerry测试用\r\n" });
    c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
    {
        Description = "JWT Authorization header using the Bearer scheme.",
        Name = "Authorization",
        In = ParameterLocation.Header,
        Scheme = "bearer",
        Type = SecuritySchemeType.Http,
        BearerFormat = "JWT"
    });

    c.AddSecurityRequirement(new OpenApiSecurityRequirement {
                        {
                            new OpenApiSecurityScheme
                            {
                                Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" }
                            },
                            new List<string>()
                        } });
});



博客园:https://www.cnblogs.com/wosperry/p/net6_jwt.html