AntDesign Pro + .NET Core 实现基于JWT的登录认证成果

许多同学说AgileConfig的UI实在是太丑了。我想想也是的,原来这个项目是我本身利用的,一开始甚至连UI都没有,全靠手动在数据库里修改数据。厥后加上了UI也是利用了老掉牙的bootstrap3做为基本样式。前台框架也是利用了angularjs,同样是老掉牙的对象。过年期间终于下刻意翻新AgileConfig的前端UI。最后选择的前端UI框架为AntDesign Pro + React。至于为啥选Ant-Design Pro是因为他悦目,并且风行,选择React是因为VUE跟Angular我都略知一二,爽性趁此时机学一学React为何物,为何这么风行。
登录的认证方案为JWT,其实本人对JWT不太伤风(请看这里《我们真的需要jwt吗?》),无奈各人都喜欢,那我也只能随大流。
其实基于ant-design pro的界面我已经翻的差不多了,因为它支持mock数据,所以我一行靠山代码都没修改,已经把界面快写完了。以后刻开始要真正的跟后端代码举办联调了。那么我们先从登录开始吧。先看看后端asp.net core方面会如何举办修改。

修改ASP.NET Core后端代码

"JwtSetting": { "SecurityKey": "xxxxxxxxxxxx", // 密钥 "Issuer": "agileconfig.admin", // 揭晓者 "Audience": "agileconfig.admin", // 吸收者 "ExpireSeconds": 20 // 逾期时间 s }

在appsettings.json文件添加jwt相关设置。

public class JwtSetting { static JwtSetting() { Instance = new JwtSetting(); Instance.Audience = Global.Config["JwtSetting:Audience"]; Instance.SecurityKey = Global.Config["JwtSetting:SecurityKey"]; Instance.Issuer = Global.Config["JwtSetting:Issuer"]; Instance.ExpireSeconds = int.Parse(Global.Config["JwtSetting:ExpireSeconds"]); } public string SecurityKey { get; set; } public string Issuer { get; set; } public string Audience { get; set; } public int ExpireSeconds { get; set; } public static JwtSetting Instance { get; } }

界说一个JwtSetting类,用来读取设置。

public void ConfigureServices(IServiceCollection services) { services.AddMemoryCache(); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidIssuer = JwtSetting.Instance.Issuer, ValidAudience = JwtSetting.Instance.Audience, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(JwtSetting.Instance.SecurityKey)), }; }); services.AddCors(); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0).AddRazorRuntimeCompilation(); services.AddFreeSqlDbContext(); services.AddBusinessServices(); services.AddAntiforgery(o => o.SuppressXFrameOptionsHeader = true); }

修改Startup文件的ConfigureServices要领,修改认证Scheme为JwtBearerDefaults.AuthenticationScheme,在AddJwtBearer要领内设置jwt相关设置信息。因为前后端疏散项目所以有大概api跟ui陈设在差异的域名下,所以开启Cors。

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IServiceProvider serviceProvider) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseMiddleware<ExceptionHandlerMiddleware>(); } app.UseCors(op=> { op.AllowAnyOrigin(); op.AllowAnyMethod(); op.AllowAnyHeader(); }); app.UseWebSockets(new WebSocketOptions() { KeepAliveInterval = TimeSpan.FromSeconds(60), ReceiveBufferSize = 2 * 1024 }); app.UseMiddleware<WebsocketHandlerMiddleware>(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapDefaultControllerRoute(); }); }

修改Startup的Configure要领,设置Cors为Any。

public class JWT { public static string GetToken() { //建设用户身份标识,可按需要添加更多信息 var claims = new Claim[] { new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), new Claim("id", "admin", ClaimValueTypes.String), // 用户id new Claim("name", "admin"), // 用户名 new Claim("admin", true.ToString() ,ClaimValueTypes.Boolean) // 是否是打点员 }; var key = Encoding.UTF8.GetBytes(JwtSetting.Instance.SecurityKey); //建设令牌 var token = new JwtSecurityToken( issuer: JwtSetting.Instance.Issuer, audience: JwtSetting.Instance.Audience, signingCredentials: new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature), claims: claims, notBefore: DateTime.Now, expires: DateTime.Now.AddSeconds(JwtSetting.Instance.ExpireSeconds) ); string jwtToken = new JwtSecurityTokenHandler().WriteToken(token); return jwtToken; } }

添加一个JWT静态类用来生成jwt的token。因为agileconfig的用户只有admin一个所以这里用户名,ID都直接写死。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wsjjpx.html