1.Start up 里面配置JWT认证方案
//认证方案 services.AddAuthentication(option => { option.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; option.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer( option => { option.TokenValidationParameters = new TokenValidationParameters { //是否验证发行人 ValidateIssuer = true, ValidIssuer = Configuration["JwtConfig:Issuer"],//发行人 //是否验证受众人 ValidateAudience = true, ValidAudience = Configuration["JwtConfig:Audience"],//受众人 //是否验证密钥 ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JwtConfig:key"])), ValidateLifetime = true, //验证生命周期 RequireExpirationTime = true, //过期时间 ClockSkew = TimeSpan.Zero //平滑过期偏移时间 }; } );
2.appsettings.json配置JWT
"JwtConfig": { "key": "JWTStudyWebsite_DI20DXU3", "Issuer": "mahang", "Audience": "wlw" }
3. 生成令牌, 示例:登录成功生成令牌
/// <summary> /// 登录 /// </summary> /// <param name="RegisterEntity"></param> /// <param name="RegisterUserPassword"></param> /// <returns></returns> public ResultDto Login(LoginDto loginDto) { ResultDto result = new ResultDto(); var registerName = registerRepository.Query(x => (x.RegisterUserName == loginDto.RegisterEntity || x.RegisterUserEmail == loginDto.RegisterEntity || x.RegisterUserPhone == loginDto.RegisterEntity)).FirstOrDefault(); var registerPassWord = registerRepository.Query(x => x.RegisterUserPassword == MD5HashUtility.MD5Hash(loginDto.RegisterUserPassword)); if (registerName == null && registerPassWord.Count() == 0) { result.Message = "未注册,请先注册!"; return result; } else { if (registerName == null) { result.Message = "用户名输入错误,请重新输入!"; return result; } else { if (MD5HashUtility.MD5Hash(loginDto.RegisterUserPassword) != registerName.RegisterUserPassword) { result.Message = "密码输入错误,请重新输入!"; return result; } else { //写Session或Cookies换成JWT IList<Claim> claims = new List<Claim> { new Claim(JwtClaimTypes.Id,registerName.RegisterUserName), new Claim(JwtClaimTypes.Name,registerName.RegisterUserPassword) }; //JWT密钥 var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["JwtConfig:key"])); //算法 var cred = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); //过期时间 DateTime expires = DateTime.UtcNow.AddHours(10); //Payload负载 var token = new JwtSecurityToken( issuer: configuration["JwtConfig:Issuer"], audience: configuration["JwtConfig:Audience"], claims: claims, notBefore: DateTime.UtcNow, expires: expires, signingCredentials: cred ); var handler = new JwtSecurityTokenHandler(); //生成令牌 string jwt = handler.WriteToken(token); result.Code = 200; result.Message = "登录成功!"; result.Success = new LoginDto { RegisterEntity = loginDto.RegisterEntity, RegisterUserPassword = loginDto.RegisterUserPassword, Token = jwt }; } } } return result; } }
4.Start up 在AddSwaggerGen中配置小锁
services.AddSwaggerGen(options => { options.SwaggerDoc("v1", new OpenApiInfo { Title = "InterviewSystem.WebApi", Version = "v1" }); //xml显示swgger注释 options.IncludeXmlComments(System.IO.Directory.GetCurrentDirectory() + @"\\bin\\Debug\\net5.0\\InterviewSystem.WebApi.xml"); //开启权限小锁 options.OperationFilter<AddResponseHeadersFilter>(); options.OperationFilter<AppendAuthorizeToSummaryOperationFilter>(); options.OperationFilter<SecurityRequirementsOperationFilter>(); //在header中添加token,传递到后台 options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme { Description = "JWT授权(数据将在请求头中进行传递)直接在下面框中输入Bearer {token}(注意两者之间是一个空格) \"", Name = "Authorization",//jwt默认的参数名称 In = ParameterLocation.Header,//jwt默认存放Authorization信息的位置(请求头中) Type = SecuritySchemeType.ApiKey }); });
5.配置相应的认证中间件和授权中间件
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseSwagger(); app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "InterviewSystem.WebApi v1")); } //启用静态文件浏览功能 app.UseStaticFiles(); //Https中间件 app.UseHttpsRedirection(); // 跨域 app.UseCors(); //路由中间件 app.UseRouting(); //认证中间件 app.UseAuthentication(); //授权中间件 app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); }
5.在控制器中添加全局特性
6.在Vue中,登录成功后用localStorage存储Token
//登录
submitForm(formName) { this.$refs[formName].validate((valid) => { if (valid) { axios .post("Login/Login", this.ruleForm) .then((res) => { if (res.data.Code != 200) { this.$message.error(res.data.Message); } else { this.$message({ message: res.data.Message, type: "success", }); sessionStorage.setItem("RegisterEntity",this.ruleForm.RegisterEntity); localStorage.setItem("Token",res.data.Success.Token) this.$router.push("/main/IntroductionVue"); } }); } else { console.log("error submit!!"); return false; } }); },
7.Vue配置js文件,全局使用Token
import axios from "axios" axios.defaults.baseURL = "https://localhost:44386/api/"; axios.defaults.headers.common['Authorization'] = `Bearer ${localStorage.getItem("Token")}`; export default axios
标签:Vue,RegisterEntity,app,jwt,RegisterUserPassword,Api,result,new,loginDto From: https://www.cnblogs.com/LaoMa0109/p/16810931.html