asp.net core AuthenticationMiddleware 在WebApi中的的使用

在.net framework 4.5架构下使用认证(Authentication)授权(Authorization)。

asp.net core AuthenticationMiddleware 在WebApi中的的使用

IIS使用HttpModule进行认证(Authentication),我们可以选择自己实现认证方式并在web.config中配置,当然也可以选择IIS默认提供的几种实现,这里不再继续展开讨论。

asp.net core默认提供了几种默认的实现方式,包括Identity,Facebook, Google, Microsoft Account, Twitter 等等。这里介绍Basic Authentication认证方式。asp.net core的请求通道由一系列的请求委托组成,一个一个顺序执行。

asp.net core AuthenticationMiddleware 在WebApi中的的使用

实现Basic Authentication最简单的方式是添加一个中间件。新建文件BasicAuthenticationMiddlerware

 public sealed class BasicAuthenticationMiddlerware
{
private readonly RequestDelegate _next; public BasicAuthenticationMiddlerware(RequestDelegate next)
{
_next = next;
} public async Task InvokeAsync(HttpContext context)
{
string authentication = context.Request.Headers["Authorization"];
if (authentication != null && authentication.Contains("Basic"))
{
//Extract credentials
var usernamePasswordStr = authentication.Trim().Split(" ")[]; var userNamAndPasswordArr = usernamePasswordStr.Split(':');
if (userNamAndPasswordArr.Length != )
{
context.Response.StatusCode = ;
} var username = userNamAndPasswordArr[];
var password = userNamAndPasswordArr[]; /*
* 根据用户账号密码验证用户有效性
* 如果有效
* 执行 await _next.Invoke(context);
* 否则
* context.Response.StatusCode = 401;
*/ if (true)
{
await _next.Invoke(context);
}
else
{
context.Response.StatusCode = ;
}
}
else
{
context.Response.StatusCode = ;
} }

完成中间件的定义以后,在Startup.cs文件的Configure方法中注册中间件以开启验证。注意,这里一定要添加在app.UseMvc()之前。

app.UseMiddleware<BasicAuthenticationMiddlerware>();

或者通过添加IApplicationBuilder的扩张方法,再用扩展方法进行注册。代码如下

   public static class BasicAuthenticationMiddlerwareExtension
{
public static IApplicationBuilder UseBasicAuthenticationMiddlerware(
this IApplicationBuilder builder)
{
return builder.UseMiddleware<BasicAuthenticationMiddlerware>();
}
}

Startup.cs的Configure的内容如下

 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseBasicAuthenticationMiddlerware();
app.UseMvc();
}

启动WebApi。不添加头文件Authorization,如预期返回401状态码。

asp.net core AuthenticationMiddleware 在WebApi中的的使用

添加头部信息,如预期返回数据。

asp.net core AuthenticationMiddleware 在WebApi中的的使用

上一篇:MVC - 云服务器部署


下一篇:Markdown初入门(使用Typora编辑)