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为例:

源码在此:https://github.com/aspnet/Security/tree/rel/2.0.0-preview1/src/Microsoft.AspNetCore.Authentication.JwtBearer

在ConfigureServices中调用AddJwtBearerAuthentication,其实是调用了AddScheme,authenticationScheme是JwtBearerDefaults.AuthenticationScheme。

JwtBearerOptions是继承AuthenticationSchemeOptions的类,用来保存认证配置。
JwtBearerHandler继承了AuthenticationHandler<JwtBearerOptions>,用于认证过程处理,需要什么依赖,直接从构造函数注入。关键在HandleAuthenticateAsync和HandleUnauthorizedAsync这两个方法。
 
认证流程是这样的:
1. ConfigureServices中调用AddScheme提供<AuthenticationSchemeOptions,AuthenticationHandler>并指定Scheme。
2. Configure中调用UseAuthentication。
3. 访问一个带有AuthorizeAttribute的Action。
4. AuthenticationMiddleware获取默认Scheme(或者AuthorizeAttribute指定的Scheme)的AuthenticationHandler,调用到Handler的HandleAuthenticateAsync,根据返回结果来决定是调用HandleUnauthorizedAsync还是HandleForbiddenAsync。
 
我们自己实现认证方案主要就是要实现HandleAuthenticateAsync这个方法,想怎么认证就怎么写。

.Net Core 2.0 preview1实现自定义认证方案的更多相关文章

  1. .net core 1.0 Web MVC 自定义认证过程

    通过官方的介绍可知,若要本地开始部署搭建一个基于.net core 1.0的Web应用,需要下载dotnet SDK,或在Visual Studio IDE之上安装相关插件以布置开发环境.为了使开发环 ...

  2. 把旧系统迁移到.Net Core 2.0 日记 (18) --JWT 认证(Json Web Token)

    我们最常用的认证系统是Cookie认证,通常用一般需要人工登录的系统,用户访问授权范围的url时,会自动Redirect到Account/Login,登录后把认证结果存在cookie里. 系统只要找到 ...

  3. ASP.Net Core 3.0 中使用JWT认证

    JWT认证简单介绍     关于Jwt的介绍网上很多,此处不在赘述,我们主要看看jwt的结构.     JWT主要由三部分组成,如下: HEADER.PAYLOAD.SIGNATURE HEADER包 ...

  4. .net core 3.0更改默认身份认证的的表。

    public class ApplicationDbContext : IdentityDbContext<WebUser, WebRole, Guid, WebUserClaim, WebUs ...

  5. EntityFramework Core 2.0自定义标量函数两种方式

    前言 上一节我们讲完原始查询如何防止SQL注入问题同时并提供了几种方式.本节我们继续来讲讲EF Core 2.0中的新特性自定义标量函数. 自定义标量函数两种方式 在EF Core 2.0中我们可以将 ...

  6. ASP.NET Core 1.0 静态文件、路由、自定义中间件、身份验证简介

    概述 ASP.NET Core 1.0是ASP.NET的一个重要的重新设计. 例如,在ASP.NET Core中,使用Middleware编写请求管道. ASP.NET Core中间件对HttpCon ...

  7. asp.net core 2.0 web api基于JWT自定义策略授权

    JWT(json web token)是一种基于json的身份验证机制,流程如下: 通过登录,来获取Token,再在之后每次请求的Header中追加Authorization为Token的凭据,服务端 ...

  8. Asp.Net Core 2.0 项目实战(10) 基于cookie登录授权认证并实现前台会员、后台管理员同时登录

    1.登录的实现 登录功能实现起来有哪些常用的方式,大家首先想到的肯定是cookie或session或cookie+session,当然还有其他模式,今天主要探讨一下在Asp.net core 2.0下 ...

  9. asp.net core 自定义认证方式--请求头认证

    asp.net core 自定义认证方式--请求头认证 Intro 最近开始真正的实践了一些网关的东西,最近写几篇文章分享一下我的实践以及遇到的问题. 本文主要介绍网关后面的服务如何进行认证. 解决思 ...

随机推荐

  1. VB 读取列表文件名

    Private Sub Command1_Click()Dim d As String, s As String If Dir(App.Path & "\down", vb ...

  2. -1.记libgdx初次接触

    学习一门技术最难的是开发环境变量配置和工具配置,以下为我初次接触libgdx时遇到的问题 几个难点记录下 gradle 直接用下到本地,然后放到d盘,链接到就行(gradle-wrapper.prop ...

  3. Shiro学习

    Shiro学习资源 Shiro官网,http://shiro.apache.org/index.html 学习网站链接,http://blog.java1234.com/blog/articles/4 ...

  4. HTTP协议 与 TCP协议 的区别

    TCP协议是传输层协议,主要解决数据如何在网络中传输,而HTTP是应用层协议,主要解决如何包装数据. TCP/IP和HTTP协议的关系,从本质上来说,二者没有可比性,我们在传输数据时,可以只使用(传输 ...

  5. mount的几个选项

    一.mount -o noatime表示在读文件时不去更改文件的access time属性了,所以该选项会提升mount操作的执行效率. 二.mount --bind:等同于 -o bind可用于挂载 ...

  6. JAVA:简单添加菜单界面(swing)第二版

    环境:jdk1.8 package com.le.tool; import java.awt.Color; import java.awt.Container; import java.awt.Flo ...

  7. Centos7 网络报错Job for iptables.service failed because the control process exited with error code.

    今天在进行项目联系的时候,启动在待机的虚拟机,发现虚拟机的网络设置又出现了问题. 我以为像往常一样重启网卡服务就能成功,但是它却报了Job for iptables.service failed be ...

  8. linux之Ubuntu学习

    开始学习Linux系统是在通过虚拟机VMware上安装Ubuntu操作系统来学习的. 一.Ubuntu安装及使用 第一步:安装虚拟机VMware 第二步:虚拟机安装好之后,创建一个新的虚拟机,安装Ub ...

  9. Python学习笔记-函数基础

    函数基础 定义: 函数是指将一组语句的集合通过一个名字(函数名)封装起来,要想执行这个函数,只需调用其函数名即可 为什么使用函数:减少重复代码.使程序变的可扩展使程序变得易维护 1.定义一个函数 #定 ...

  10. python 上传文件

    上周产品给我提了个需求,大体是做一个后台系统,管理游戏比赛落地页的数据更新,难点在于需要给CDN上传文件.现在把经验记录下来,下次有类似的需求能提高开发效率. 我使用的是网宿CDN,没有用网宿的SDK ...