使用WebApi+Vue3從0到1搭建《許可權管理系統》:二、搭建JWT系統鑑權

陈逸子风發表於2024-04-18

影片地址:【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的詳細程式碼

相關文章