asp.net core AuthenticationMiddleware 在WebApi中的的使用
2017-09-22 00:00
851 查看
在.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最简单的方式是添加一个中间件。新建文件BasicAuthenticationMiddlerwarepublic 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(" ")[1];
var userNamAndPasswordArr = usernamePasswordStr.Split(':');
if (userNamAndPasswordArr.Length != 2)
{
context.Response.StatusCode = 401;
}
var username = userNamAndPasswordArr[0];
var password = userNamAndPasswordArr[1];
/*
* 根据用户账号密码验证用户有效性
* 如果有效
* 执行 await _next.Invoke(context);
* 否则
* context.Response.StatusCode = 401;
*/
if (true)
{
await _next.Invoke(context);
}
else
{
context.Response.StatusCode = 401;
}
}
else
{
context.Response.StatusCode = 401;
}
}
}完成中间件的定义以后,在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状态码。

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

原文地址:http://www.cnblogs.com/Zhang-Xiang/p/7536803.html
.NET社区新闻,深度好文,微信中搜索dotNET跨平台或扫描二维码关注
IIS使用HttpModule进行认证(Authentication),我们可以选择自己实现认证方式并在web.config中配置,当然也可以选择IIS默认提供的几种实现,这里不再继续展开讨论。 asp.net core默认提供了几种默认的实现方式,包括Identity,Facebook, Google, Microsoft Account, Twitter 等等。这里介绍Basic Authentication认证方式。asp.net core的请求通道由一系列的请求委托组成,一个一个顺序执行。
实现Basic Authentication最简单的方式是添加一个中间件。新建文件BasicAuthenticationMiddlerwarepublic 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(" ")[1];
var userNamAndPasswordArr = usernamePasswordStr.Split(':');
if (userNamAndPasswordArr.Length != 2)
{
context.Response.StatusCode = 401;
}
var username = userNamAndPasswordArr[0];
var password = userNamAndPasswordArr[1];
/*
* 根据用户账号密码验证用户有效性
* 如果有效
* 执行 await _next.Invoke(context);
* 否则
* context.Response.StatusCode = 401;
*/
if (true)
{
await _next.Invoke(context);
}
else
{
context.Response.StatusCode = 401;
}
}
else
{
context.Response.StatusCode = 401;
}
}
}完成中间件的定义以后,在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状态码。
添加头部信息,如预期返回数据。
原文地址:http://www.cnblogs.com/Zhang-Xiang/p/7536803.html
.NET社区新闻,深度好文,微信中搜索dotNET跨平台或扫描二维码关注
相关文章推荐
- 在ASP.NET Core使用Middleware模拟Custom Error Page功能
- 使用Visual Studio Code开发Asp.Net Core WebApi学习笔记(六)-- 依赖注入
- 在ASP.NET Core 2.0中使用CookieAuthentication
- [转]在ASP.NET Core使用Middleware模拟Custom Error Page功能
- Asp.Net Core Authentication Middleware And Generate Token
- Asp.Net Core Authentication Middleware And Generate Token
- ASP.NET Core -中间件(Middleware)使用
- ASP.NET Core中Middleware的使用
- Asp.net core WebApi 使用Swagger生成帮助页
- 使用Visual Studio Code开发Asp.Net Core WebApi学习笔记(四)-- Middleware
- C#编译器优化那点事 c# 如果一个对象的值为null,那么它调用扩展方法时为甚么不报错 webAPI 控制器(Controller)太多怎么办? .NET MVC项目设置包含Areas中的页面为默认启动页 (五)Net Core使用静态文件 学习ASP.NET Core Razor 编程系列八——并发处理
- ASP.NET Core Kestrel 中使用 HTTPS (SSL)
- 使用angular4和asp.net core 2 web api做个练习项目(三)
- 详解在ASP.NET Core下使用SignalR技术
- 在ASP.NET Core中使用Apworks开发数据服务:对HAL的支持
- ASP.NET Core Kestrel 中使用 HTTPS (SSL)
- ASP.NET Core 中使用 GrayLog 记录日志
- ASP.NET CORE系列【三】使用Entity Framework Core进行增删改查
- asp.net core 使用EntityFrameWork遇到的问题
- ASP.NET Core 中文文档 第二章 指南(4.5)使用 SQL Server LocalDB