使用WebApi+Vue3从0到1搭建《权限管理系统》:二、搭建JWT系统鉴权

视频地址:【WebApi+Vue3从0到1搭建《权限管理系统》系列视频:搭建JWT系统鉴权-哔哩哔哩】 https://b23.tv/R6cOcDO

qq群:801913255

一、在appsettings.json中设置鉴权属性

 /*jwt鉴权*/
 "JwtSetting": {
   "Issuer": "zhangsan", //发行人
   "Audience": "zhangsan", //订阅人
   "ExpireSeconds": 120, //过期时间,默认分钟
   "ENAlgorithm": "HS256", //秘钥算法 
   "SecurityKey": "Zmz=Start2024013OverallAuth.WebApi" //秘钥构成
 },

二、新建模型

添加模型JwtSettingModel其中字段和appsettings.json中的字段一样,如下

/// <summary>
/// jwt 配置模型
/// </summary>
public class JwtSettingModel
{
    /// <summary>
    /// 发行人
    /// </summary>
    public string Issuer { get; set; }

    /// <summary>
    /// 订阅人
    /// </summary>
    public string Audience { get; set; }

    /// <summary>
    /// 过期时间,默认分钟
    /// </summary>
    public int  ExpireSeconds { get; set; }

    /// <summary>
    /// 秘钥算法
    /// </summary>
    public string ENAlgorithm { get; set; }

    /// <summary>
    /// 秘钥构成
    /// </summary>
    public string SecurityKey { get; set; }

}

三、新建解析appsettings.json节点的帮助类

 /// <summary>
 /// 配置文件解析帮助类
 /// </summary>
 public class ConfigurationHelper
 {
     /// <summary>
     /// 配置项
     /// </summary>
     public static IConfiguration configuration { get; set; }

     /// <summary>
     /// 构造实例化
     /// </summary>
     static ConfigurationHelper() 
     {
         configuration = new ConfigurationBuilder().Add(new JsonConfigurationSource { Path = "appsettings.json", ReloadOnChange = true }).Build();
     }

     /// <summary>
     /// 获取appsetings 配置节点
     /// </summary>
     /// <typeparam name="T"></typeparam>
     /// <param name="node"></param>
     /// <returns></returns>
     public static T GetNode<T>(string node) where T : new() 
     {
         T mode = configuration.GetSection(node).Get<T>();
         return mode;
     }

 }

四、在Startup.cs编写鉴权代码

找到ConfigureServices方法,在方法中添加如下代码

 //添加jwt鉴权
 services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, option =>
 {
     var jwtsetting = ConfigurationHelper.GetNode<JwtSettingModel>("JwtSetting");
     Configuration.Bind("JwtSetting", jwtsetting);
     option.SaveToken = true;
     option.TokenValidationParameters = new TokenValidationParameters()
     {
         ValidIssuer = jwtsetting.Issuer,//发行人
         ValidAudience = jwtsetting.Audience,//订阅人
         IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtsetting.SecurityKey)),//解密的密钥
         ValidateIssuerSigningKey = true,//是否验证签名,不验证的画可以篡改数据,不安全
         ValidateIssuer = true,//是否验证发行人,就是验证载荷中的Iss是否对应ValidIssuer参数
         ValidateAudience = true,//是否验证订阅人,就是验证载荷中的Aud是否对应ValidAudience参数
         ValidateLifetime = true,//是否验证过期时间,过期了就拒绝访问
         ClockSkew = TimeSpan.Zero,//这个是token缓冲过期时间,如果设置了,token过期时间就是缓冲时间+过期时间
         //RequireExpirationTime = true,
     };

 });

并在Configure方法中添加jwt授权代码 app.UseAuthorization();

五、编写Jwt帮助类

/// <summary>
/// jwt帮助类
/// </summary>
public static class JwtHelper
{
    /// <summary>
    /// 生成token
    /// </summary>
    /// <param name="loginResult"></param>
    /// <returns></returns>
    public static string BuildToken(LoginModel loginResult)
    {
        LoginModel result = new();
        var jwtsetting = ConfigurationHelper.GetNode<JwtSettingModel>("JwtSetting");

        //获取登录信息
        var calime = loginResult.PropValueType().Select(x => new Claim(x.Name, x.Value.ToString(), x.Type)).ToList();

        //记录登录信息
        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtsetting.SecurityKey));
        var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
        var header = new JwtHeader(creds);
        var paylod = new JwtPayload(jwtsetting.Issuer, jwtsetting.Audience, calime, DateTime.Now, DateTime.Now.AddMinutes(jwtsetting.ExpireSeconds));

        //正式创建令牌
        var token = new JwtSecurityToken(header, paylod);
        var tokenStr = new JwtSecurityTokenHandler().WriteToken(token);
        var  ddd = token.ValidTo.AddHours(8).ToString();
        return tokenStr;
    }

    /// <summary>
    /// 反射获取字段信息
    /// </summary>
    /// <param name="obj">模型</param>
    /// <returns></returns>
    public static IEnumerable<(string Name, object Value, string Type)> PropValueType(this object obj)
    {
        List<(string a, object b, string c)> result = new();
        var type = obj.GetType();
        var props = type.GetProperties();
        foreach (var item in props)
        {
            result.Add((item.Name, item.GetValue(obj), item.PropertyType.Name));
        }
        return result;
    }
}

然后再webapi接口控制器上方添加鉴权特性[Authorize],这样所有接口都会遵守jwt鉴权协议

 

六、Swagger接口文档使用Jwt鉴权

做好以上五点,webapi中就能正常使用jwt鉴权,但如果你使用Swagger测试接口,那么就要让Swagger遵守Jwt协议

所以必须在添加以下代码,注意这段代码是写在AddSwaggerGen中

 //把jwt添加到swagger中
 optinos.AddSecurityDefinition("OverallAuth.WebApi", new OpenApiSecurityScheme
 {
     Description = "直接在下框中输入Bearer token(注意两者之间是一个空格)",
     Name = "Authorization",//jwt默认的参数名称
     In = ParameterLocation.Header,//jwt默认存放请求头中
     Type = SecuritySchemeType.ApiKey
 });

 //swagger遵守jwt授权协议
 optinos.AddSecurityRequirement(new OpenApiSecurityRequirement
     {
        {
             new OpenApiSecurityScheme{
                 Reference = new OpenApiReference {
                             Type = ReferenceType.SecurityScheme,
                             Id = "OverallAuth.WebApi"
                 }
            },new string[] { }
         }
     });

以上就是在webapi中使用jwt的详细代码

 

posted @ 2024-04-18 15:02  陈逸子风  阅读(1118)  评论(3编辑  收藏  举报