視頻地址:【WebApi+Vue3從0到1搭建《許可權管理系統》系列視頻:搭建JWT系統鑒權-嗶哩嗶哩】 https://b23.tv/R6cOcDO qq群:801913255 一、在appsettings.json中設置鑒權屬性 /*jwt鑒權*/ "JwtSetting": { "Issuer" ...
視頻地址:【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的詳細代碼