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. CentOS7 + Django2.1 + uwsgi + nginx配置

    假设已经可以运行Django项目,可以runserver.也已经安装了uwsgi和nginx 现在需要进行配置. 刚开始进行uwsgi测试就不行,提示bash:'uwsgi' Command not ...

  2. redis学习-string常用命令

    keys * :查询所有的key值 set:为指定键设置对应的值 get:获取指定键的值 mset:一次传入多个键值对 mget:一次获取多个键的值 del:删除指定键 strlen:获取指定键值的长 ...

  3. 在Linux下部署mysql时,使用group by碰到的问题

    mysql使用group by 的时候报错,错误信息如下: 1055:ER_WRONG_FIELD_WITH_GROUP: Expression #2 of SELECT list is not in ...

  4. [转]MYSQL性能查看(命中率,慢查询)

    网上有很多的文章教怎么配置MySQL服务器,但考虑到服务器硬件配置的不同,具体应用的差别,那些文章的做法只能作为初步设置参考,我们需要根据自己的情况进行配置优化,好的做法是MySQL服务器稳定运行了一 ...

  5. centos 安装部署zabbix

    Zabbix_server初始安装部署 各模块要安装的模块 Server:server+nginx+mysql+php Agentd:agentd Proxy:proxy+mysql 1.准备环境: ...

  6. Django积木块五——分页

    分页 django本身带有分页功能,为什么要用他呢?因为它的代码更为简洁,并且在做筛选的时候会把url中的所有参数都组装起来,并且加上分页.也就是做筛选中的结果也可以用这个分页. pip instal ...

  7. maven配置parent pom查找策略

    当我们在pom.xml中添加parent pom的时候,通常maven会按照如下顺序查找parent依赖: relativePath标签指向的路径. 默认的relativePath路径".. ...

  8. numpy、pandas

    numpy: 仨属性:ndim-维度个数:shape-维度大小:dtype-数据类型. numpy和pandas各def的axis缺省为0,作用于列,除DataFrame的.sort_index()和 ...

  9. 算法第四版jar包下载地址

    算法第四版jar包下载地址:https://algs4.cs.princeton.edu/code/

  10. webapi使用swagger出现“Cannot read property 'parameters' of null”

    前端时间在webapi项目使用swagger来提供接口文档及测试工具,按网上方法(http://wmpratt.com/swagger-and-asp-net-web-api-part-1)配置好之后 ...