AntDesign Pro + .NET Core 實現基於JWT的登入認證
阿新 • • 發佈:2021-03-04
很多同學說AgileConfig的UI實在是太醜了。我想想也是的,本來這個專案是我自己使用的,一開始甚至連UI都沒有,全靠手動在資料庫裡修改資料。後來加上了UI也是使用了老掉牙的bootstrap3做為基礎樣式。前臺框架也是使用了angularjs,同樣是老掉牙的東西。過年期間終於下決心翻新AgileConfig的前端UI。最後選擇的前端UI框架為AntDesign Pro + React。至於為啥選Ant-Design Pro是因為他好看,而且流行,選擇React是因為VUE跟Angular我都略知一二,乾脆趁此機會學一學React為何物,為何這麼流行。
登入的認證方案為JWT,其實本人對JWT不太感冒(請看這裡《[我們真的需要jwt嗎?](https://www.cnblogs.com/kklldog/p/should-we-need-jwt-always.html)》),無奈大家都喜歡,那我也只能隨大流。
其實基於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