在.net framework 4.5架構下使用認證(Authentication)受權(Authorization)。web
IIS使用HttpModule進行認證(Authentication),咱們能夠選擇本身實現認證方式並在web.config中配置,固然也能夠選擇IIS默認提供的幾種實現,這裏再也不繼續展開討論。架構
asp.net core默認提供了幾種默認的實現方式,包括Identity,Facebook, Google, Microsoft Account, Twitter 等等。這裏介紹Basic Authentication認證方式。asp.net core的請求通道由一系列的請求委託組成,一個一個順序執行。app
實現Basic Authentication最簡單的方式是添加一箇中間件。新建文件BasicAuthenticationMiddlerwareasp.net
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()以前。async
或者經過添加IApplicationBuilder的擴張方法,再用擴展方法進行註冊。代碼以下ui
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的內容以下this
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狀態碼。spa
添加頭部信息,如預期返回數據。.net