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. javascript、JSP、JS有什么区别和联系

    js是javascript的缩写.以下是JSP与JS的区别和联系: 名字:JS:JavaScriptJSP:Java Server Pages 执行过程:JSP先翻译,翻译成Servlet执行如: t ...

  2. pycharm汉化(3.6版本)

    step 1:下载pycharm汉化包  链接:https://pan.baidu.com/s/1htgcbZY 密码:8uia step 2:将pycharm安装目录下的lib文件夹内下的resou ...

  3. kali配置python3的开发环境

    最近打算学习一下python3,毕竟不会写脚本的程序员,不是一个好的安全测试人员! 对于我来说,python的大部分应用都是在linux上,而kali是我唯一一个有图形化操作界面的linux系统 所以 ...

  4. window下github的学习心得

    准备工作: 安装git: 1.下载地址:http://msysgit.github.io/ 2.安装:本人是一路next的,现在没发现有什么问题.详细的安装过程参考:https://jingyan.b ...

  5. android6.0以上权限动态申请,有视频链接可以看效果。

    android6.0以上某些权限需要动态申请,虽然现在大多的手机系统版本在6.0,但是升级到6.0及以上是迟早的事,所以如何能够更好的控制动态申请权限时能有好的提示用户,及给用户带去更好的体验,是需要 ...

  6. MySQL平时记录笔记

    零,mysql的安装 http://blog.csdn.net/mhmyqn/article/details/17043921 https://www.cnblogs.com/wangjunyan/p ...

  7. 【转】RPC介绍

    转自:http://www.cnblogs.com/Vincentlu/p/4185299.html 摘要: RPC——Remote Procedure Call Protocol,这是广义上的解释, ...

  8. latex 常用自定义_随时更新

    1.向量定义 代码: \newcommand{\vector}[1]{${#1}_1,{#1}_2,\cdots,{#1}_n$} 效果: a1,a2,...,an

  9. easyui的下拉框combox动态复赋值显示在前端

    editbale:false设置为本输入框禁止编辑

  10. 1.Spring AOP应用

    首先咱们来了解一下具体的业务场景(这是个真实的项目的业务场景):具体的业务是这样的,现在系统中有六十多个主档(功能模块),每个主档都有新增.修改.删除功能,当我们在对每个主档做这些操作时需要对其记录日 ...