欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

使用 Ant Design Pro 和 .NET Core,通过 JWT 实现简单易用的登录验证

最编程 2024-07-28 10:33:43
...

很多同学说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部署在不同的域名下,所以开启Core。

  // 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,    no.........

推荐阅读