.Net Core 2.0 preview1实现自定义认证方案
Microsoft.Authentication的使用方法在2.0中发生了比较大的变化,在1.1中认证配置是在Configure中完成。
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication();
} public void Configure(IApplicationBuilder app)
{
app.UseJwtBearerAuthentication(new JwtBearerOptions
{
Authority = Configuration["jwt:authority"],
Audience = Configuration["jwt:audience"],
Events = new JwtBearerEvents()
{
OnAuthenticationFailed = c =>
{
c.HandleResponse();
c.Response.StatusCode = 500;
c.Response.ContentType = "text/plain";
if (Environment.IsDevelopment())
{
return c.Response.WriteAsync(c.Exception.ToString());
}
return c.Response.WriteAsync("An error occurred processing your authentication.");
}
}
});
UseJwtBearerAuthentication其实是添加了一个中间件
public static IApplicationBuilder UseJwtBearerAuthentication(this IApplicationBuilder app, JwtBearerOptions options)
{
if (app == null)
{
throw new ArgumentNullException(nameof(app));
}
if (options == null)
{
throw new ArgumentNullException(nameof(options));
} return app.UseMiddleware<JwtBearerMiddleware>(Options.Create(options));
}
而在2.0中,认证配置则是在ConfigureServices中完成,并且通过Scheme-Handler的形式来实现多种认证方案的策略式选择。
public void ConfigureServices(IServiceCollection services)
{
services.AddJwtBearerAuthentication(o =>
{
o.Authority = Configuration["jwt:authority"];
o.Audience = Configuration["jwt:audience"];
o.Events = new JwtBearerEvents()
{
OnAuthenticationFailed = c =>
{
c.HandleResponse();
c.Response.StatusCode = 500;
c.Response.ContentType = "text/plain";
if (Environment.IsDevelopment())
{
return c.Response.WriteAsync(c.Exception.ToString());
}
return c.Response.WriteAsync("An error occurred processing your authentication.");
}
};
});
} public void Configure(IApplicationBuilder app)
{
app.UseAuthentication();
}
public static IServiceCollection AddJwtBearerAuthentication(this IServiceCollection services, string authenticationScheme, Action<JwtBearerOptions> configureOptions)
{
return services.AddScheme<JwtBearerOptions, JwtBearerHandler>(authenticationScheme, configureOptions);
}
public static IApplicationBuilder UseAuthentication(this IApplicationBuilder app)
{
if (app == null)
{
throw new ArgumentNullException(nameof(app));
}
return app.UseMiddleware<AuthenticationMiddleware>();
}
namespace Microsoft.AspNetCore.Authentication
{
public class AuthenticationMiddleware
{
private readonly RequestDelegate _next; public AuthenticationMiddleware(RequestDelegate next, IAuthenticationSchemeProvider schemes)
{
if (next == null)
{
throw new ArgumentNullException(nameof(next));
}
if (schemes == null)
{
throw new ArgumentNullException(nameof(schemes));
} _next = next;
Schemes = schemes;
} public IAuthenticationSchemeProvider Schemes { get; set; } public async Task Invoke(HttpContext context)
{
context.Features.Set<IAuthenticationFeature>(new AuthenticationFeature
{
OriginalPath = context.Request.Path,
OriginalPathBase = context.Request.PathBase
}); // REVIEW: alternatively could depend on a routing middleware to do this // Give any IAuthenticationRequestHandler schemes a chance to handle the request
var handlers = context.RequestServices.GetRequiredService<IAuthenticationHandlerProvider>();
foreach (var scheme in await Schemes.GetRequestHandlerSchemesAsync())
{
var handler = await handlers.GetHandlerAsync(context, scheme.Name) as IAuthenticationRequestHandler;
if (handler != null && await handler.HandleRequestAsync())
{
return;
}
} var defaultAuthenticate = await Schemes.GetDefaultAuthenticateSchemeAsync();
if (defaultAuthenticate != null)
{
var result = await context.AuthenticateAsync(defaultAuthenticate.Name);
if (result?.Principal != null)
{
context.User = result.Principal;
}
} await _next(context);
}
}
}
也就是说,1.1的时候我们使用不同的认证方案时,是使用不同的中间件来实现认证,而2.0则刚好反过来,官方实现了一个统一的认证中间件,在中间件里获取对应的Scheme的Handler,然后调用Handler来完成认证过程。
在2.0中实现自己的认证方案非常方便——自己实现一个AuthenticationSchemeOptions和一个AuthenticationHandler,然后通过AddScheme注入并指定Scheme就可以了。
以官方JwtBearerAuthentication为例:
在ConfigureServices中调用AddJwtBearerAuthentication,其实是调用了AddScheme,authenticationScheme是JwtBearerDefaults.AuthenticationScheme。
.Net Core 2.0 preview1实现自定义认证方案的更多相关文章
- .net core 1.0 Web MVC 自定义认证过程
通过官方的介绍可知,若要本地开始部署搭建一个基于.net core 1.0的Web应用,需要下载dotnet SDK,或在Visual Studio IDE之上安装相关插件以布置开发环境.为了使开发环 ...
- 把旧系统迁移到.Net Core 2.0 日记 (18) --JWT 认证(Json Web Token)
我们最常用的认证系统是Cookie认证,通常用一般需要人工登录的系统,用户访问授权范围的url时,会自动Redirect到Account/Login,登录后把认证结果存在cookie里. 系统只要找到 ...
- ASP.Net Core 3.0 中使用JWT认证
JWT认证简单介绍 关于Jwt的介绍网上很多,此处不在赘述,我们主要看看jwt的结构. JWT主要由三部分组成,如下: HEADER.PAYLOAD.SIGNATURE HEADER包 ...
- .net core 3.0更改默认身份认证的的表。
public class ApplicationDbContext : IdentityDbContext<WebUser, WebRole, Guid, WebUserClaim, WebUs ...
- EntityFramework Core 2.0自定义标量函数两种方式
前言 上一节我们讲完原始查询如何防止SQL注入问题同时并提供了几种方式.本节我们继续来讲讲EF Core 2.0中的新特性自定义标量函数. 自定义标量函数两种方式 在EF Core 2.0中我们可以将 ...
- ASP.NET Core 1.0 静态文件、路由、自定义中间件、身份验证简介
概述 ASP.NET Core 1.0是ASP.NET的一个重要的重新设计. 例如,在ASP.NET Core中,使用Middleware编写请求管道. ASP.NET Core中间件对HttpCon ...
- asp.net core 2.0 web api基于JWT自定义策略授权
JWT(json web token)是一种基于json的身份验证机制,流程如下: 通过登录,来获取Token,再在之后每次请求的Header中追加Authorization为Token的凭据,服务端 ...
- Asp.Net Core 2.0 项目实战(10) 基于cookie登录授权认证并实现前台会员、后台管理员同时登录
1.登录的实现 登录功能实现起来有哪些常用的方式,大家首先想到的肯定是cookie或session或cookie+session,当然还有其他模式,今天主要探讨一下在Asp.net core 2.0下 ...
- asp.net core 自定义认证方式--请求头认证
asp.net core 自定义认证方式--请求头认证 Intro 最近开始真正的实践了一些网关的东西,最近写几篇文章分享一下我的实践以及遇到的问题. 本文主要介绍网关后面的服务如何进行认证. 解决思 ...
随机推荐
- ContentType与SpiringMvc
转载https://blog.csdn.net/mingtianhaiyouwo/article/details/51459764
- 批处理-Java JDK环境变量配置
setx /M JAVA_HOME "C:\Program Files\Java\jdk1.8.0_131" setx /M CLASSPATH ".;%%JAVA_HO ...
- angular点击查看更多(简单demo)
今天来跟大家分享一个小的demo,一般网页浏览到底部的时候会有一个点击加载更多的按钮,之前一直纠结怎么写这个,今天学习angular时发现可以用组件来实现这么一个小的效果,大家有兴趣的话可以看一下. ...
- SpringBoot+Mybatis配置Pagehelper分页插件实现自动分页
SpringBoot+Mybatis配置Pagehelper分页插件实现自动分页 **SpringBoot+Mybatis使用Pagehelper分页插件自动分页,非常好用,不用在自己去计算和组装了. ...
- 一篇关于Asp.Net Model验证响应消息的问题处理
之前,我做过Asp.Net Core的Model验证,在Core中过滤器对响应的处理很简单 context.Result = new JsonResult(ErrorMsg); 但是,在Asp.Net ...
- oracle控制台命令
sqlplus /nolog -- 无密码登陆 sqlplus "/as sysdba" -- 以管理员身份登录 shutdown immediate; --关闭数据库 sel ...
- explicit_defaults_for_timestamp引发的狗血剧情
今天就碰到了一个较初级的问题,居然为找这个参数花了好半天时间,深以为不齿.需求是这样的,有个表的某个字段需要从datetime改成timestamp类型.原结构如下:create table tmp1 ...
- ffmpeg源码编译安装(Compile ffmpeg with source) Part 1 : 通用部分
本页内容包含了在Unix/Linux中用源码包编译的通用的结构 可能不仅仅适用于ffmpeg 为啥使用源码包编译 编译源码可以扩展功能, 实现相对于自己平台的最优化, 还可以自定义的修改 概述 大部分 ...
- [转]Java工程师技术栈--成神之路
一.基础篇 1.1 JVM 1.1.1. Java内存模型,Java内存管理,Java堆和栈,垃圾回收 http://www.jcp.org/en/jsr/detail?id=133http://if ...
- 在windows上安装VTK
看了很多教程,花了1天半的时间装上了,记录下. 前置条件:我安装了VS2015,用来编译工程. 参考资料 官方:http://www.vtk.org/Wiki/VTK/Building 安装:http ...