在.net framework 4.5架構下使用認證(Authentication)授權(Authorization)。
IIS使用HttpModule進行認證(Authentication),我們可以選擇自己實現認證方式並在web.config中配置,當然也可以選擇IIS默認提供的幾種實現,這里不再繼續展開討論。
asp.net core默認提供了幾種默認的實現方式,包括Identity,Facebook, Google, Microsoft Account, Twitter 等等。這里介紹Basic Authentication認證方式。asp.net core的請求通道由一系列的請求委托組成,一個一個順序執行。
實現Basic Authentication最簡單的方式是添加一個中間件。新建文件BasicAuthenticationMiddlerware
1 public sealed class BasicAuthenticationMiddlerware 2 { 3 private readonly RequestDelegate _next; 4 5 public BasicAuthenticationMiddlerware(RequestDelegate next) 6 { 7 _next = next; 8 } 9 10 public async Task InvokeAsync(HttpContext context) 11 { 12 string authentication = context.Request.Headers["Authorization"]; 13 if (authentication != null && authentication.Contains("Basic")) 14 { 15 //Extract credentials 16 var usernamePasswordStr = authentication.Trim().Split(" ")[1]; 17 18 var userNamAndPasswordArr = usernamePasswordStr.Split(':'); 19 if (userNamAndPasswordArr.Length != 2) 20 { 21 context.Response.StatusCode = 401; 22 } 23 24 var username = userNamAndPasswordArr[0]; 25 var password = userNamAndPasswordArr[1]; 26 27 /* 28 * 根據用戶賬號密碼驗證用戶有效性 29 * 如果有效 30 * 執行 await _next.Invoke(context); 31 * 否則 32 * context.Response.StatusCode = 401; 33 */ 34 35 if (true) 36 { 37 await _next.Invoke(context); 38 } 39 else 40 { 41 context.Response.StatusCode = 401; 42 } 43 } 44 else 45 { 46 context.Response.StatusCode = 401; 47 } 48 49 } 50 }
完成中間件的定義以后,在Startup.cs文件的Configure方法中注冊中間件以開啟驗證。注意,這里一定要添加在app.UseMvc()之前。
app.UseMiddleware<BasicAuthenticationMiddlerware>();
或者通過添加IApplicationBuilder的擴張方法,再用擴展方法進行注冊。代碼如下
1 public static class BasicAuthenticationMiddlerwareExtension 2 { 3 public static IApplicationBuilder UseBasicAuthenticationMiddlerware( 4 this IApplicationBuilder builder) 5 { 6 return builder.UseMiddleware<BasicAuthenticationMiddlerware>(); 7 } 8 }
Startup.cs的Configure的內容如下
1 public void Configure(IApplicationBuilder app, IHostingEnvironment env) 2 { 3 if (env.IsDevelopment()) 4 { 5 app.UseDeveloperExceptionPage(); 6 } 7 app.UseBasicAuthenticationMiddlerware(); 8 app.UseMvc(); 9 }
啟動WebApi。不添加頭文件Authorization,如預期返回401狀態碼。
添加頭部信息,如預期返回數據。