欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

【.NET Core项目实战-统一认证平台】第八章 授权篇-IdentityServer4源码分析

程序员文章站 2022-03-12 14:55:31
" 【.NET Core项目实战 统一认证平台】开篇及目录索引 " 上篇文章我介绍了如何在网关上实现客户端自定义限流功能,基本完成了关于网关的一些自定义扩展需求,后面几篇将介绍基于 的认证相关知识,在具体介绍 实现我们统一认证的相关功能前,我们首先需要分析下 源码,便于我们彻底掌握认证的原理以及后续 ......

【.net core项目实战-统一认证平台】开篇及目录索引

上篇文章我介绍了如何在网关上实现客户端自定义限流功能,基本完成了关于网关的一些自定义扩展需求,后面几篇将介绍基于identityserver4(后面简称ids4)的认证相关知识,在具体介绍ids4实现我们统一认证的相关功能前,我们首先需要分析下ids4源码,便于我们彻底掌握认证的原理以及后续的扩展需求。

.netcore项目实战交流群(637326624),有兴趣的朋友可以在群里交流讨论。

一、ids4文档及源码

文档地址

github源码地址 https://github.com/identityserver/identityserver4

二、源码整体分析

【工欲善其事,必先利其器,器欲尽其能,必先得其法】

在我们使用ids4前我们需要了解它的运行原理和实现方式,这样实际生产环境中才能安心使用,即使遇到问题也可以很快解决,如需要对认证进行扩展,也可自行编码实现。

源码分析第一步就是要找到ids4的中间件是如何运行的,所以需要定位到中间价应用位置app.useidentityserver();,查看到详细的代码如下。

/// <summary>
/// adds identityserver to the pipeline.
/// </summary>
/// <param name="app">the application.</param>
/// <returns></returns>
public static iapplicationbuilder useidentityserver(this iapplicationbuilder app)
{
    //1、验证配置信息
    app.validate();
    //2、应用baseurl中间件
    app.usemiddleware<baseurlmiddleware>();
    //3、应用跨域访问配置
    app.configurecors();
    //4、启用系统认证功能
    app.useauthentication();
    //5、应用ids4中间件
    app.usemiddleware<identityservermiddleware>();

    return app;
}

通过上面的源码,我们知道整体流程分为这5步实现。接着我们分析下每一步都做了哪些操作呢?

1、app.validate()为我们做了哪些工作?

  • 校验ipersistedgrantstore、iclientstore、iresourcestore是否已经注入?

  • 验证identityserveroptions配置信息是否都配置完整

  • 输出调试相关信息提醒

    internal static void validate(this iapplicationbuilder app)
    {
        var loggerfactory = app.applicationservices.getservice(typeof(iloggerfactory)) as iloggerfactory;
        if (loggerfactory == null) throw new argumentnullexception(nameof(loggerfactory));
    
        var logger = loggerfactory.createlogger("identityserver4.startup");
    
        var scopefactory = app.applicationservices.getservice<iservicescopefactory>();
    
        using (var scope = scopefactory.createscope())
        {
            var serviceprovider = scope.serviceprovider;
    
            testservice(serviceprovider, typeof(ipersistedgrantstore), logger, "no storage mechanism for grants specified. use the 'addinmemorypersistedgrants' extension method to register a development version.");
            testservice(serviceprovider, typeof(iclientstore), logger, "no storage mechanism for clients specified. use the 'addinmemoryclients' extension method to register a development version.");
            testservice(serviceprovider, typeof(iresourcestore), logger, "no storage mechanism for resources specified. use the 'addinmemoryidentityresources' or 'addinmemoryapiresources' extension method to register a development version.");
    
            var persistedgrants = serviceprovider.getservice(typeof(ipersistedgrantstore));
            if (persistedgrants.gettype().fullname == typeof(inmemorypersistedgrantstore).fullname)
            {
                logger.loginformation("you are using the in-memory version of the persisted grant store. this will store consent decisions, authorization codes, refresh and reference tokens in memory only. if you are using any of those features in production, you want to switch to a different store implementation.");
            }
    
            var options = serviceprovider.getrequiredservice<identityserveroptions>();
            validateoptions(options, logger);
    
            validateasync(serviceprovider, logger).getawaiter().getresult();
        }
    }
    
    private static async task validateasync(iserviceprovider services, ilogger logger)
    {
        var options = services.getrequiredservice<identityserveroptions>();
        var schemes = services.getrequiredservice<iauthenticationschemeprovider>();
    
        if (await schemes.getdefaultauthenticateschemeasync() == null && options.authentication.cookieauthenticationscheme == null)
        {
            logger.logwarning("no authentication scheme has been set. setting either a default authentication scheme or a cookieauthenticationscheme on identityserveroptions is required.");
        }
        else
        {
            if (options.authentication.cookieauthenticationscheme != null)
            {
                logger.loginformation("using explicitly configured scheme {scheme} for identityserver", options.authentication.cookieauthenticationscheme);
            }
    
            logger.logdebug("using {scheme} as default asp.net core scheme for authentication", (await schemes.getdefaultauthenticateschemeasync())?.name);
            logger.logdebug("using {scheme} as default asp.net core scheme for sign-in", (await schemes.getdefaultsigninschemeasync())?.name);
            logger.logdebug("using {scheme} as default asp.net core scheme for sign-out", (await schemes.getdefaultsignoutschemeasync())?.name);
            logger.logdebug("using {scheme} as default asp.net core scheme for challenge", (await schemes.getdefaultchallengeschemeasync())?.name);
            logger.logdebug("using {scheme} as default asp.net core scheme for forbid", (await schemes.getdefaultforbidschemeasync())?.name);
        }
    }
    
    private static void validateoptions(identityserveroptions options, ilogger logger)
    {
        if (options.issueruri.ispresent()) logger.logdebug("custom issueruri set to {0}", options.issueruri);
    
        if (options.publicorigin.ispresent())
        {
            if (!uri.trycreate(options.publicorigin, urikind.absolute, out var uri))
            {
                throw new invalidoperationexception($"publicorigin is not valid: {options.publicorigin}");
            }
    
            logger.logdebug("publicorigin explicitly set to {0}", options.publicorigin);
        }
    
        // todo: perhaps different logging messages?
        //if (options.userinteraction.loginurl.ismissing()) throw new invalidoperationexception("loginurl is not configured");
        //if (options.userinteraction.loginreturnurlparameter.ismissing()) throw new invalidoperationexception("loginreturnurlparameter is not configured");
        //if (options.userinteraction.logouturl.ismissing()) throw new invalidoperationexception("logouturl is not configured");
        if (options.userinteraction.logoutidparameter.ismissing()) throw new invalidoperationexception("logoutidparameter is not configured");
        if (options.userinteraction.errorurl.ismissing()) throw new invalidoperationexception("errorurl is not configured");
        if (options.userinteraction.erroridparameter.ismissing()) throw new invalidoperationexception("erroridparameter is not configured");
        if (options.userinteraction.consenturl.ismissing()) throw new invalidoperationexception("consenturl is not configured");
        if (options.userinteraction.consentreturnurlparameter.ismissing()) throw new invalidoperationexception("consentreturnurlparameter is not configured");
        if (options.userinteraction.customredirectreturnurlparameter.ismissing()) throw new invalidoperationexception("customredirectreturnurlparameter is not configured");
    
        if (options.authentication.checksessioncookiename.ismissing()) throw new invalidoperationexception("checksessioncookiename is not configured");
    
        if (options.cors.corspolicyname.ismissing()) throw new invalidoperationexception("corspolicyname is not configured");
    }
    
    internal static object testservice(iserviceprovider serviceprovider, type service, ilogger logger, string message = null, bool dothrow = true)
    {
        var appservice = serviceprovider.getservice(service);
    
        if (appservice == null)
        {
            var error = message ?? $"required service {service.fullname} is not registered in the di container. aborting startup";
    
            logger.logcritical(error);
    
            if (dothrow)
            {
                throw new invalidoperationexception(error);
            }
        }
    
        return appservice;
    }

    详细的实现代码如上所以,非常清晰明了,这时候有人肯定会问这些相关的信息时从哪来的呢?这块我们会在后面讲解。

    2、baseurlmiddleware中间件实现了什么功能?

源码如下,就是从配置信息里校验是否设置了publicorigin原始实例地址,如果设置了修改下请求的schemehost,最后设置identityserverbasepath地址信息,然后把请求转到下一个路由。

namespace identityserver4.hosting
{
    public class baseurlmiddleware
    {
        private readonly requestdelegate _next;
        private readonly identityserveroptions _options;

        public baseurlmiddleware(requestdelegate next, identityserveroptions options)
        {
            _next = next;
            _options = options;
        }

        public async task invoke(httpcontext context)
        {
            var request = context.request;

            if (_options.publicorigin.ispresent())
            {
                context.setidentityserverorigin(_options.publicorigin);
            }

            context.setidentityserverbasepath(request.pathbase.value.removetrailingslash());

            await _next(context);
        }
    }
}

这里源码非常简单,就是设置了后期要处理的一些关于请求地址信息。那这个中间件有什么作用呢?

就是设置认证的通用地址,当我们访问认证服务配置地址http://localhost:5000/.well-known/openid-configuration的时候您会发现,您设置的publicorigin会自定应用到所有的配置信息前缀,比如设置option.publicorigin = "http://www.baidu.com";,显示的json代码如下。

{"issuer":"http://www.baidu.com","jwks_uri":"http://www.baidu.com/.well-known/openid-configuration/jwks","authorization_endpoint":"http://www.baidu.com/connect/authorize","token_endpoint":"http://www.baidu.com/connect/token","userinfo_endpoint":"http://www.baidu.com/connect/userinfo","end_session_endpoint":"http://www.baidu.com/connect/endsession","check_session_iframe":"http://www.baidu.com/connect/checksession","revocation_endpoint":"http://www.baidu.com/connect/revocation","introspection_endpoint":"http://www.baidu.com/connect/introspect","frontchannel_logout_supported":true,"frontchannel_logout_session_supported":true,"backchannel_logout_supported":true,"backchannel_logout_session_supported":true,"scopes_supported":["api1","offline_access"],"claims_supported":[],"grant_types_supported":["authorization_code","client_credentials","refresh_token","implicit"],"response_types_supported":["code","token","id_token","id_token token","code id_token","code token","code id_token token"],"response_modes_supported":["form_post","query","fragment"],"token_endpoint_auth_methods_supported":["client_secret_basic","client_secret_post"],"subject_types_supported":["public"],"id_token_signing_alg_values_supported":["rs256"],"code_challenge_methods_supported":["plain","s256"]}

可能还有些朋友觉得奇怪,这有什么用啊?其实不然,试想下如果您部署的认证服务器是由多台组成,那么可以设置这个地址为负载均衡地址,这样访问每台认证服务器的配置信息,返回的负载均衡的地址,而负载均衡真正路由到的地址是内网地址,每一个实例内网地址都不一样,这样就可以负载生效,后续的文章会介绍配合consul实现自动的服务发现和注册,达到动态扩展认证节点功能。

可能表述的不太清楚,可以先试着理解下,因为后续篇幅有介绍负载均衡案例会讲到实际应用。

3、app.configurecors(); 做了什么操作?

其实这个从字面意思就可以看出来,是配置跨域访问的中间件,源码就是应用配置的跨域策略。

namespace identityserver4.hosting
{
    public static class corsmiddlewareextensions
    {
        public static void configurecors(this iapplicationbuilder app)
        {
            var options = app.applicationservices.getrequiredservice<identityserveroptions>();
            app.usecors(options.cors.corspolicyname);
        }
    }
}

很简单吧,至于什么是跨域,可自行查阅相关文档,由于篇幅有效,这里不详细解释。

4、app.useauthentication();做了什么操作?

就是启用了默认的认证中间件,然后在相关的控制器增加[authorize]属性标记即可完成认证操作,由于本篇是介绍的ids4的源码,所以关于非ids4部分后续有需求再详细介绍实现原理。

5、identityservermiddleware中间件做了什么操作?

这也是ids4的核心中间件,通过源码分析,哎呀!好简单啊,我要一口气写100个牛逼中间件。哈哈,我当时也是这么想的,难道真的这么简单吗?接着往下分析,让我们彻底明白ids4是怎么运行的。

namespace identityserver4.hosting
{
    /// <summary>
    /// identityserver middleware
    /// </summary>
    public class identityservermiddleware
    {
        private readonly requestdelegate _next;
        private readonly ilogger _logger;

        /// <summary>
        /// initializes a new instance of the <see cref="identityservermiddleware"/> class.
        /// </summary>
        /// <param name="next">the next.</param>
        /// <param name="logger">the logger.</param>
        public identityservermiddleware(requestdelegate next, ilogger<identityservermiddleware> logger)
        {
            _next = next;
            _logger = logger;
        }

        /// <summary>
        /// invokes the middleware.
        /// </summary>
        /// <param name="context">the context.</param>
        /// <param name="router">the router.</param>
        /// <param name="session">the user session.</param>
        /// <param name="events">the event service.</param>
        /// <returns></returns>
        public async task invoke(httpcontext context, iendpointrouter router, iusersession session, ieventservice events)
        {
            // this will check the authentication session and from it emit the check session
            // cookie needed from js-based signout clients.
            await session.ensuresessionidcookieasync();

            try
            {
                var endpoint = router.find(context);
                if (endpoint != null)
                {
                    _logger.loginformation("invoking identityserver endpoint: {endpointtype} for {url}", endpoint.gettype().fullname, context.request.path.tostring());

                    var result = await endpoint.processasync(context);

                    if (result != null)
                    {
                        _logger.logtrace("invoking result: {type}", result.gettype().fullname);
                        await result.executeasync(context);
                    }

                    return;
                }
            }
            catch (exception ex)
            {
                await events.raiseasync(new unhandledexceptionevent(ex));
                _logger.logcritical(ex, "unhandled exception: {exception}", ex.message);
                throw;
            }

            await _next(context);
        }
    }
}

第一步从本地提取授权记录,就是如果之前授权过,直接提取授权到请求上下文。说起来是一句话,但是实现起来还是比较多步骤的,我简单描述下整个流程如下。

  1. 执行授权

    如果发现本地未授权时,获取对应的授权处理器,然后执行授权,看是否授权成功,如果授权成功,赋值相关的信息,常见的应用就是自动登录的实现。

    比如用户u访问a系统信息,自动跳转到s认证系统进行认证,认证后调回a系统正常访问,这时候如果用户u访问b系统(b系统也是s统一认证的),b系统会自动跳转到s认证系统进行认证,比如跳转到/login页面,这时候通过检测发现用户u已经经过认证,可以直接提取认证的所有信息,然后跳转到系统b,实现了自动登录过程。

    private async task authenticateasync()
    {
        if (principal == null || properties == null)
        {
            var scheme = await getcookieschemeasync();
         //根据请求上下人和认证方案获取授权处理器
            var handler = await handlers.gethandlerasync(httpcontext, scheme);
            if (handler == null)
            {
                throw new invalidoperationexception($"no authentication handler is configured to authenticate for the scheme: {scheme}");
            }
         //执行对应的授权操作
            var result = await handler.authenticateasync();
            if (result != null && result.succeeded)
            {
                principal = result.principal;
                properties = result.properties;
            }
        }
    }
    1. 获取路由处理器

      其实这个功能就是拦截请求,获取对应的请求的处理器,那它是如何实现的呢?

      iendpointrouter是这个接口专门负责处理的,那这个方法的实现方式是什么呢?可以右键-转到实现,我们可以找到endpointrouter方法,详细代码如下。

      namespace identityserver4.hosting
      {
          internal class endpointrouter : iendpointrouter
          {
              private readonly ienumerable<endpoint> _endpoints;
              private readonly identityserveroptions _options;
              private readonly ilogger _logger;
      
              public endpointrouter(ienumerable<endpoint> endpoints, identityserveroptions options, ilogger<endpointrouter> logger)
              {
                  _endpoints = endpoints;
                  _options = options;
                  _logger = logger;
              }
      
              public iendpointhandler find(httpcontext context)
              {
                  if (context == null) throw new argumentnullexception(nameof(context));
                //遍历所有的路由和请求处理器,如果匹配上,返回对应的处理器,否则返回null
                  foreach(var endpoint in _endpoints)
                  {
                      var path = endpoint.path;
                      if (context.request.path.equals(path, stringcomparison.ordinalignorecase))
                      {
                          var endpointname = endpoint.name;
                          _logger.logdebug("request path {path} matched to endpoint type {endpoint}", context.request.path, endpointname);
      
                          return getendpointhandler(endpoint, context);
                      }
                  }
      
                  _logger.logtrace("no endpoint entry found for request path: {path}", context.request.path);
      
                  return null;
              }
            //根据判断配置文件是否开启了路由拦截功能,如果存在提取对应的处理器。
              private iendpointhandler getendpointhandler(endpoint endpoint, httpcontext context)
              {
                  if (_options.endpoints.isendpointenabled(endpoint))
                  {
                      var handler = context.requestservices.getservice(endpoint.handler) as iendpointhandler;
                      if (handler != null)
                      {
                          _logger.logdebug("endpoint enabled: {endpoint}, successfully created handler: {endpointhandler}", endpoint.name, endpoint.handler.fullname);
                          return handler;
                      }
                      else
                      {
                          _logger.logdebug("endpoint enabled: {endpoint}, failed to create handler: {endpointhandler}", endpoint.name, endpoint.handler.fullname);
                      }
                  }
                  else
                  {
                      _logger.logwarning("endpoint disabled: {endpoint}", endpoint.name);
                  }
      
                  return null;
              }
          }
      }

      源码功能我做了简单的讲解,发现就是提取对应路由处理器,然后转换成iendpointhandler接口,所有的处理器都会实现这个接口。但是ienumerable<endpoint>记录是从哪里来的呢?而且为什么可以获取到指定的处理器,可以查看如下代码,原来都注入到默认的路由处理方法里。

      /// <summary>
      /// adds the default endpoints.
      /// </summary>
      /// <param name="builder">the builder.</param>
      /// <returns></returns>
      public static iidentityserverbuilder adddefaultendpoints(this iidentityserverbuilder builder)
      {
          builder.services.addtransient<iendpointrouter, endpointrouter>();
      
          builder.addendpoint<authorizecallbackendpoint>(endpointnames.authorize, protocolroutepaths.authorizecallback.ensureleadingslash());
          builder.addendpoint<authorizeendpoint>(endpointnames.authorize, protocolroutepaths.authorize.ensureleadingslash());
          builder.addendpoint<checksessionendpoint>(endpointnames.checksession, protocolroutepaths.checksession.ensureleadingslash());
          builder.addendpoint<discoverykeyendpoint>(endpointnames.discovery, protocolroutepaths.discoverywebkeys.ensureleadingslash());
          builder.addendpoint<discoveryendpoint>(endpointnames.discovery, protocolroutepaths.discoveryconfiguration.ensureleadingslash());
          builder.addendpoint<endsessioncallbackendpoint>(endpointnames.endsession, protocolroutepaths.endsessioncallback.ensureleadingslash());
          builder.addendpoint<endsessionendpoint>(endpointnames.endsession, protocolroutepaths.endsession.ensureleadingslash());
          builder.addendpoint<introspectionendpoint>(endpointnames.introspection, protocolroutepaths.introspection.ensureleadingslash());
          builder.addendpoint<tokenrevocationendpoint>(endpointnames.revocation, protocolroutepaths.revocation.ensureleadingslash());
          builder.addendpoint<tokenendpoint>(endpointnames.token, protocolroutepaths.token.ensureleadingslash());
          builder.addendpoint<userinfoendpoint>(endpointnames.userinfo, protocolroutepaths.userinfo.ensureleadingslash());
      
          return builder;
      }
      
      /// <summary>
      /// adds the endpoint.
      /// </summary>
      /// <typeparam name="t"></typeparam>
      /// <param name="builder">the builder.</param>
      /// <param name="name">the name.</param>
      /// <param name="path">the path.</param>
      /// <returns></returns>
      public static iidentityserverbuilder addendpoint<t>(this iidentityserverbuilder builder, string name, pathstring path)
          where t : class, iendpointhandler
              {
                  builder.services.addtransient<t>();
                  builder.services.addsingleton(new endpoint(name, path, typeof(t)));
      
                  return builder;
              }

      通过现在分析,我们知道了路由查找方法的原理了,以后我们想增加自定义的拦截器也知道从哪里下手了。

  2. 执行路由过程并返回结果

    有了这些基础知识后,就可以很好的理解var result = await endpoint.processasync(context);这句话了,其实业务逻辑还是在自己的处理器里,但是可以通过调用接口方法实现,是不是非常优雅呢?

    为了更进一步理解,我们就上面列出的路由发现地址(http://localhost:5000/.well-known/openid-configuration)为例,讲解下运行过程。通过注入方法可以发现,路由发现的处理器如下所示。

builder.addendpoint<discoveryendpoint>(endpointnames.discovery, protocolroutepaths.discoveryconfiguration.ensureleadingslash());
//协议默认路由地址
public static class protocolroutepaths
{
    public const string authorize              = "connect/authorize";
    public const string authorizecallback      = authorize + "/callback";
    public const string discoveryconfiguration = ".well-known/openid-configuration";
    public const string discoverywebkeys       = discoveryconfiguration + "/jwks";
    public const string token                  = "connect/token";
    public const string revocation             = "connect/revocation";
    public const string userinfo               = "connect/userinfo";
    public const string introspection          = "connect/introspect";
    public const string endsession             = "connect/endsession";
    public const string endsessioncallback     = endsession + "/callback";
    public const string checksession           = "connect/checksession";

    public static readonly string[] corspaths =
    {
        discoveryconfiguration,
        discoverywebkeys,
        token,
        userinfo,
        revocation
    };
}

可以请求的地址会被拦截,然后进行处理。

它的详细代码如下,跟分析的一样是实现了iendpointhandler接口。

   using system.net;
   using system.threading.tasks;
   using identityserver4.configuration;
   using identityserver4.endpoints.results;
   using identityserver4.extensions;
   using identityserver4.hosting;
   using identityserver4.responsehandling;
   using microsoft.aspnetcore.http;
   using microsoft.extensions.logging;
   
   namespace identityserver4.endpoints
   {
       internal class discoveryendpoint : iendpointhandler
       {
           private readonly ilogger _logger;
   
           private readonly identityserveroptions _options;
   
           private readonly idiscoveryresponsegenerator _responsegenerator;
   
           public discoveryendpoint(
               identityserveroptions options,
               idiscoveryresponsegenerator responsegenerator,
               ilogger<discoveryendpoint> logger)
           {
               _logger = logger;
               _options = options;
               _responsegenerator = responsegenerator;
           }
   
           public async task<iendpointresult> processasync(httpcontext context)
           {
               _logger.logtrace("processing discovery request.");
   
               // 1、验证请求是否为get方法
               if (!httpmethods.isget(context.request.method))
               {
                   _logger.logwarning("discovery endpoint only supports get requests");
                   return new statuscoderesult(httpstatuscode.methodnotallowed);
               }
   
               _logger.logdebug("start discovery request");
            //2、判断是否开启了路由发现功能
               if (!_options.endpoints.enablediscoveryendpoint)
               {
                   _logger.loginformation("discovery endpoint disabled. 404.");
                   return new statuscoderesult(httpstatuscode.notfound);
               }
   
               var baseurl = context.getidentityserverbaseurl().ensuretrailingslash();
               var issueruri = context.getidentityserverissueruri();
   
               
               _logger.logtrace("calling into discovery response generator: {type}", _responsegenerator.gettype().fullname);
               // 3、生成路由相关的输出信息
               var response = await _responsegenerator.creatediscoverydocumentasync(baseurl, issueruri);
            //5、返回路由发现的结果信息
               return new discoverydocumentresult(response, _options.discovery.responsecacheinterval);
           }
       }
   }

通过上面代码说明,可以发现通过4步完成了整个解析过程,然后输出最终结果,终止管道继续往下进行。

   if (result != null)
   {
       _logger.logtrace("invoking result: {type}", result.gettype().fullname);
       await result.executeasync(context);
   }
  
   return;

路由发现的具体实现代码如下,就是把结果转换成json格式输出,然后就得到了我们想要的结果。

   /// <summary>
   /// executes the result.
   /// </summary>
   /// <param name="context">the http context.</param>
   /// <returns></returns>
   public task executeasync(httpcontext context)
   {
       if (maxage.hasvalue && maxage.value >= 0)
       {
           context.response.setcache(maxage.value);
       }
   
       return context.response.writejsonasync(objectserializer.tojobject(entries));
   }

到此完整的路由发现功能及实现了,其实这个实现比较简单,因为没有涉及太多其他关联的东西,像获取token和就相对复杂一点,然后分析方式一样。

6、继续运行下一个中间件

有了上面的分析,我们可以知道整个授权的流程,所有在我们使用ids4时需要注意中间件的执行顺序,针对需要授权后才能继续操作的中间件需要放到ids4中间件后面。

三、获取token执行分析

为什么把这块单独列出来呢?因为后续很多扩展和应用都是基础token获取的流程,所以有必要单独把这块拿出来进行讲解。有了前面整体的分析,现在应该直接这块源码是从哪里看了,没错就是下面这句。

 builder.addendpoint<tokenendpoint>(endpointnames.token, protocolroutepaths.token.ensureleadingslash());

他的执行过程是tokenendpoint,所以我们重点来分析下这个是怎么实现这么复杂的获取token过程的,首先放源码。

// copyright (c) brock allen & dominick baier. all rights reserved.
// licensed under the apache license, version 2.0. see license in the project root for license information.


using identitymodel;
using identityserver4.endpoints.results;
using identityserver4.events;
using identityserver4.extensions;
using identityserver4.hosting;
using identityserver4.responsehandling;
using identityserver4.services;
using identityserver4.validation;
using microsoft.aspnetcore.http;
using microsoft.extensions.logging;
using system.collections.generic;
using system.threading.tasks;

namespace identityserver4.endpoints
{
    /// <summary>
    /// the token endpoint
    /// </summary>
    /// <seealso cref="identityserver4.hosting.iendpointhandler" />
    internal class tokenendpoint : iendpointhandler
    {
        private readonly iclientsecretvalidator _clientvalidator;
        private readonly itokenrequestvalidator _requestvalidator;
        private readonly itokenresponsegenerator _responsegenerator;
        private readonly ieventservice _events;
        private readonly ilogger _logger;

        /// <summary>
        /// 构造函数注入 <see cref="tokenendpoint" /> class.
        /// </summary>
        /// <param name="clientvalidator">客户端验证处理器</param>
        /// <param name="requestvalidator">请求验证处理器</param>
        /// <param name="responsegenerator">输出生成处理器</param>
        /// <param name="events">事件处理器.</param>
        /// <param name="logger">日志</param>
        public tokenendpoint(
            iclientsecretvalidator clientvalidator, 
            itokenrequestvalidator requestvalidator, 
            itokenresponsegenerator responsegenerator, 
            ieventservice events, 
            ilogger<tokenendpoint> logger)
        {
            _clientvalidator = clientvalidator;
            _requestvalidator = requestvalidator;
            _responsegenerator = responsegenerator;
            _events = events;
            _logger = logger;
        }

        /// <summary>
        /// processes the request.
        /// </summary>
        /// <param name="context">the http context.</param>
        /// <returns></returns>
        public async task<iendpointresult> processasync(httpcontext context)
        {
            _logger.logtrace("processing token request.");

            // 1、验证是否为post请求且必须是form-data方式
            if (!httpmethods.ispost(context.request.method) || !context.request.hasformcontenttype)
            {
                _logger.logwarning("invalid http request for token endpoint");
                return error(oidcconstants.tokenerrors.invalidrequest);
            }

            return await processtokenrequestasync(context);
        }

        private async task<iendpointresult> processtokenrequestasync(httpcontext context)
        {
            _logger.logdebug("start token request.");

            // 2、验证客户端授权是否正确
            var clientresult = await _clientvalidator.validateasync(context);

            if (clientresult.client == null)
            {
                return error(oidcconstants.tokenerrors.invalidclient);
            }

            /* 3、验证请求信息,详细代码(tokenrequestvalidator.cs)
                原理就是根据不同的grant_type,调用不同的验证方式
            */
            var form = (await context.request.readformasync()).asnamevaluecollection();
            _logger.logtrace("calling into token request validator: {type}", _requestvalidator.gettype().fullname);
            var requestresult = await _requestvalidator.validaterequestasync(form, clientresult);

            if (requestresult.iserror)
            {
                await _events.raiseasync(new tokenissuedfailureevent(requestresult));
                return error(requestresult.error, requestresult.errordescription, requestresult.customresponse);
            }

            // 4、创建输出结果 tokenresponsegenerator.cs
            _logger.logtrace("calling into token request response generator: {type}", _responsegenerator.gettype().fullname);
            var response = await _responsegenerator.processasync(requestresult);
            //发送token生成事件
            await _events.raiseasync(new tokenissuedsuccessevent(response, requestresult));
            //5、写入日志,便于调试
            logtokens(response, requestresult);

            // 6、返回最终的结果
            _logger.logdebug("token request success.");
            return new tokenresult(response);
        }

        private tokenerrorresult error(string error, string errordescription = null, dictionary<string, object> custom = null)
        {
            var response = new tokenerrorresponse
            {
                error = error,
                errordescription = errordescription,
                custom = custom
            };

            return new tokenerrorresult(response);
        }

        private void logtokens(tokenresponse response, tokenrequestvalidationresult requestresult)
        {
            var clientid = $"{requestresult.validatedrequest.client.clientid} ({requestresult.validatedrequest.client?.clientname ?? "no name set"})";
            var subjectid = requestresult.validatedrequest.subject?.getsubjectid() ?? "no subject";

            if (response.identitytoken != null)
            {
                _logger.logtrace("identity token issued for {clientid} / {subjectid}: {token}", clientid, subjectid, response.identitytoken);
            }
            if (response.refreshtoken != null)
            {
                _logger.logtrace("refresh token issued for {clientid} / {subjectid}: {token}", clientid, subjectid, response.refreshtoken);
            }
            if (response.accesstoken != null)
            {
                _logger.logtrace("access token issued for {clientid} / {subjectid}: {token}", clientid, subjectid, response.accesstoken);
            }
        }
    }
}

执行步骤如下:

  1. 验证是否为post请求且使用form-data方式传递参数(直接看代码即可)

  2. 验证客户端授权

    详细的验证流程代码和说明如下。

    clientsecretvalidator.cs

    public async task<clientsecretvalidationresult> validateasync(httpcontext context)
    {
        _logger.logdebug("start client validation");
    
        var fail = new clientsecretvalidationresult
        {
            iserror = true
        };
     // 从上下文中判断是否存在 client_id 和 client_secret信息(postbodysecretparser.cs)
        var parsedsecret = await _parser.parseasync(context);
        if (parsedsecret == null)
        {
            await raisefailureeventasync("unknown", "no client id found");
    
            _logger.logerror("no client identifier found");
            return fail;
        }
    
        // 通过client_id从客户端获取(iclientstore,客户端接口,下篇会介绍如何重写)
        var client = await _clients.findenabledclientbyidasync(parsedsecret.id);
        if (client == null)
        {//不存在直接输出错误 
            await raisefailureeventasync(parsedsecret.id, "unknown client");
    
            _logger.logerror("no client with id '{clientid}' found. aborting", parsedsecret.id);
            return fail;
        }
    
        secretvalidationresult secretvalidationresult = null;
        if (!client.requireclientsecret || client.isimplicitonly())
        {//判断客户端是否启用验证或者匿名访问,不进行密钥验证
            _logger.logdebug("public client - skipping secret validation success");
        }
        else
        {
            //验证密钥是否一致
            secretvalidationresult = await _validator.validateasync(parsedsecret, client.clientsecrets);
            if (secretvalidationresult.success == false)
            {
                await raisefailureeventasync(client.clientid, "invalid client secret");
                _logger.logerror("client secret validation failed for client: {clientid}.", client.clientid);
    
                return fail;
            }
        }
    
        _logger.logdebug("client validation success");
    
        var success = new clientsecretvalidationresult
        {
            iserror = false,
            client = client,
            secret = parsedsecret,
            confirmation = secretvalidationresult?.confirmation
        };
     //发送验证成功事件
        await raisesuccesseventasync(client.clientid, parsedsecret.type);
        return success;
    }

    postbodysecretparser.cs

    /// <summary>
    /// tries to find a secret on the context that can be used for authentication
    /// </summary>
    /// <param name="context">the http context.</param>
    /// <returns>
    /// a parsed secret
    /// </returns>
    public async task<parsedsecret> parseasync(httpcontext context)
    {
        _logger.logdebug("start parsing for secret in post body");
    
        if (!context.request.hasformcontenttype)
        {
            _logger.logdebug("content type is not a form");
            return null;
        }
    
        var body = await context.request.readformasync();
    
        if (body != null)
        {
            var id = body["client_id"].firstordefault();
            var secret = body["client_secret"].firstordefault();
    
            // client id must be present
            if (id.ispresent())
            {
                if (id.length > _options.inputlengthrestrictions.clientid)
                {
                    _logger.logerror("client id exceeds maximum length.");
                    return null;
                }
    
                if (secret.ispresent())
                {
                    if (secret.length > _options.inputlengthrestrictions.clientsecret)
                    {
                        _logger.logerror("client secret exceeds maximum length.");
                        return null;
                    }
    
                    return new parsedsecret
                    {
                        id = id,
                        credential = secret,
                        type = identityserverconstants.parsedsecrettypes.sharedsecret
                    };
                }
                else
                {
                    // client secret is optional
                    _logger.logdebug("client id without secret found");
    
                    return new parsedsecret
                    {
                        id = id,
                        type = identityserverconstants.parsedsecrettypes.nosecret
                    };
                }
            }
        }
    
        _logger.logdebug("no secret in post body found");
        return null;
    }
    1. 验证请求的信息是否有误

      由于代码太多,只列出tokenrequestvalidator.cs部分核心代码如下,

//是不是很熟悉,不同的授权方式
switch (granttype)
{
    case oidcconstants.granttypes.authorizationcode:  //授权码模式
        return await runvalidationasync(validateauthorizationcoderequestasync, parameters);
    case oidcconstants.granttypes.clientcredentials: //客户端模式
        return await runvalidationasync(validateclientcredentialsrequestasync, parameters);
    case oidcconstants.granttypes.password:  //密码模式
        return await runvalidationasync(validateresourceownercredentialrequestasync, parameters);
    case oidcconstants.granttypes.refreshtoken: //token更新
        return await runvalidationasync(validaterefreshtokenrequestasync, parameters);
    default:
        return await runvalidationasync(validateextensiongrantrequestasync, parameters);  //扩展模式,后面的篇章会介绍扩展方式
}
  1. 创建生成的结果

tokenresponsegenerator.cs根据不同的认证方式执行不同的创建方法,由于篇幅有限,每一个是如何创建的可以自行查看源码。

/// <summary>
/// processes the response.
/// </summary>
/// <param name="request">the request.</param>
/// <returns></returns>
public virtual async task<tokenresponse> processasync(tokenrequestvalidationresult request)
{
    switch (request.validatedrequest.granttype)
    {
        case oidcconstants.granttypes.clientcredentials:
            return await processclientcredentialsrequestasync(request);
        case oidcconstants.granttypes.password:
            return await processpasswordrequestasync(request);
        case oidcconstants.granttypes.authorizationcode:
            return await processauthorizationcoderequestasync(request);
        case oidcconstants.granttypes.refreshtoken:
            return await processrefreshtokenrequestasync(request);
        default:
            return await processextensiongrantrequestasync(request);
    }
}
  1. 写入日志记录

    为了调试方便,把生成的token相关结果写入到日志里。

  2. 输出最终结果

    把整个执行后的结果进行输出,这样就完成了整个验证过程。

四、总结

通过前面的分析,我们基本掌握的ids4整体的运行流程和具体一个认证请求的流程,由于源码太多,就未展开详细的分析每一步的实现,具体的实现细节我会在后续ids4相关章节中针对每一项的实现进行讲解,本篇基本都是全局性的东西,也在讲解了了解到了客户端的认证方式,但是只是介绍了接口,至于接口如何实现没有讲解,下一篇我们将介绍ids4实现自定义的存储并使用dapper替换efcore实现与数据库的交互流程,减少不必要的请求开销。

对于本篇源码解析还有不理解的,可以进入qq群:637326624进行讨论。