在.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