asp.net core 使用identityServer4的密码模式来进行身份认证(2) 认证授权原理

   2023-02-09 学习力0
核心提示:前言:本文将会结合asp.net core 认证源码来分析起认证的原理与流程。asp.net core版本2.2对于大部分使用asp.net core开发的人来说。下面这几行代码应该很熟悉了。services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options

前言:本文将会结合asp.net core 认证源码来分析起认证的原理与流程。asp.net core版本2.2

对于大部分使用asp.net core开发的人来说。

下面这几行代码应该很熟悉了。

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options =>
                {
                    options.RequireHttpsMetadata = false;
                    options.Audience = "sp_api";
                    options.Authority = "http://localhost:5001";
                    options.SaveToken = true;
                    
                })         
 app.UseAuthentication();

废话不多说。直接看 app.UseAuthentication()的源码

 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
            });

            // 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);
        }

现在来看看var defaultAuthenticate = await Schemes.GetDefaultAuthenticateSchemeAsync(); 干了什么。

在这之前。我们更应该要知道上面代码中  public IAuthenticationSchemeProvider Schemes { get; set; } ,假如脑海中对这个IAuthenticationSchemeProvider类型的来源,有个清晰认识,对后面的理解会有很大的帮助

现在来揭秘IAuthenticationSchemeProvider 是从哪里来添加到ioc的。

  public static AuthenticationBuilder AddAuthentication(this IServiceCollection services)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }

            services.AddAuthenticationCore();
            services.AddDataProtection();
            services.AddWebEncoders();
            services.TryAddSingleton<ISystemClock, SystemClock>();
            return new AuthenticationBuilder(services);
        }

红色代码内部逻辑中就把IAuthenticationSchemeProvider添加到了IOC中。先来看看services.AddAuthenticationCore()的源码,这个源码的所在的解决方案的仓库地址是https://github.com/aspnet/HttpAbstractions,这个仓库目前已不再维护,其代码都转移到了asp.net core 仓库 。

下面为services.AddAuthenticationCore()的源码

 public static class AuthenticationCoreServiceCollectionExtensions
    {
        /// <summary>
        /// Add core authentication services needed for <see cref="IAuthenticationService"/>.
        /// </summary>
        /// <param name="services">The <see cref="IServiceCollection"/>.</param>
        /// <returns>The service collection.</returns>
        public static IServiceCollection AddAuthenticationCore(this IServiceCollection services)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }

            services.TryAddScoped<IAuthenticationService, AuthenticationService>();
            services.TryAddSingleton<IClaimsTransformation, NoopClaimsTransformation>(); // Can be replaced with scoped ones that use DbContext
            services.TryAddScoped<IAuthenticationHandlerProvider, AuthenticationHandlerProvider>();
            services.TryAddSingleton<IAuthenticationSchemeProvider, AuthenticationSchemeProvider>();
            return services;
        }

        /// <summary>
        /// Add core authentication services needed for <see cref="IAuthenticationService"/>.
        /// </summary>
        /// <param name="services">The <see cref="IServiceCollection"/>.</param>
        /// <param name="configureOptions">Used to configure the <see cref="AuthenticationOptions"/>.</param>
        /// <returns>The service collection.</returns>
        public static IServiceCollection AddAuthenticationCore(this IServiceCollection services, Action<AuthenticationOptions> configureOptions) {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }

            if (configureOptions == null)
            {
                throw new ArgumentNullException(nameof(configureOptions));
            }

            services.AddAuthenticationCore();
            services.Configure(configureOptions);
            return services;
        }
    }

完全就可以看待添加了一个全局单例的IAuthenticationSchemeProvider对象。现在让我们回到MiddleWare中探究Schemes.GetDefaultAuthenticateSchemeAsync(); 干了什么。光看方法的名字都能猜出就是获取的默认的认证策略。

进入到IAuthenticationSchemeProvider 实现的源码中,按我的经验,来看先不急看GetDefaultAuthenticateSchemeAsync()里面的内部逻辑。必须的看下IAuthenticationSchemeProvider实现类的构造函数。它的实现类是AuthenticationSchemeProvider。

先看看AuthenticationSchemeProvider的构造方法

 public class AuthenticationSchemeProvider : IAuthenticationSchemeProvider
    {
        /// <summary>
        /// Creates an instance of <see cref="AuthenticationSchemeProvider"/>
        /// using the specified <paramref name="options"/>,
        /// </summary>
        /// <param name="options">The <see cref="AuthenticationOptions"/> options.</param>
        public AuthenticationSchemeProvider(IOptions<AuthenticationOptions> options)
            : this(options, new Dictionary<string, AuthenticationScheme>(StringComparer.Ordinal))
        {
        }

        /// <summary>
        /// Creates an instance of <see cref="AuthenticationSchemeProvider"/>
        /// using the specified <paramref name="options"/> and <paramref name="schemes"/>.
        /// </summary>
        /// <param name="options">The <see cref="AuthenticationOptions"/> options.</param>
        /// <param name="schemes">The dictionary used to store authentication schemes.</param>
        protected AuthenticationSchemeProvider(IOptions<AuthenticationOptions> options, IDictionary<string, AuthenticationScheme> schemes)
        {
            _options = options.Value;

            _schemes = schemes ?? throw new ArgumentNullException(nameof(schemes));
            _requestHandlers = new List<AuthenticationScheme>();

            foreach (var builder in _options.Schemes)
            {
                var scheme = builder.Build();
                AddScheme(scheme);
            }
        }

        private readonly AuthenticationOptions _options;
        private readonly object _lock = new object();

        private readonly IDictionary<string, AuthenticationScheme> _schemes;
        private readonly List<AuthenticationScheme> _requestHandlers;

不难看出,上面的构造方法需要一个IOptions<AuthenticationOptions> 类型。没有这个类型,而这个类型是从哪里的了?

答:不知到各位是否记得addJwtBearer这个方法,再找个方法里面就注入了AuthenticationOptions找个类型。

看源码把

 public static class JwtBearerExtensions
    {
        public static AuthenticationBuilder AddJwtBearer(this AuthenticationBuilder builder)
            => builder.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, _ => { });

        public static AuthenticationBuilder AddJwtBearer(this AuthenticationBuilder builder, Action<JwtBearerOptions> configureOptions)
            => builder.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, configureOptions);

        public static AuthenticationBuilder AddJwtBearer(this AuthenticationBuilder builder, string authenticationScheme, Action<JwtBearerOptions> configureOptions)
            => builder.AddJwtBearer(authenticationScheme, displayName: null, configureOptions: configureOptions);

        public static AuthenticationBuilder AddJwtBearer(this AuthenticationBuilder builder, string authenticationScheme, string displayName, Action<JwtBearerOptions> configureOptions)
        {
            builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton<IPostConfigureOptions<JwtBearerOptions>, JwtBearerPostConfigureOptions>());
            return builder.AddScheme<JwtBearerOptions, JwtBearerHandler>(authenticationScheme, displayName, configureOptions);
        }
    }

不难通过上述代码看出它是及一个基于AuthenticationBuilder的扩展方法,而注入AuthenticationOptions的关键就在于 builder.AddScheme<JwtBearerOptions, JwtBearerHandler>(authenticationScheme, displayName, configureOptions);  这行代码,按下F12看下源码

 public virtual AuthenticationBuilder AddScheme<TOptions, THandler>(string authenticationScheme, string displayName, Action<TOptions> configureOptions)
            where TOptions : AuthenticationSchemeOptions, new()
            where THandler : AuthenticationHandler<TOptions>
            => AddSchemeHelper<TOptions, THandler>(authenticationScheme, displayName, configureOptions);    
private AuthenticationBuilder AddSchemeHelper<TOptions, THandler>(string authenticationScheme, string displayName, Action<TOptions> configureOptions)
            where TOptions : class, new()
            where THandler : class, IAuthenticationHandler
        {
            Services.Configure<AuthenticationOptions>(o =>
            {
                o.AddScheme(authenticationScheme, scheme => {
                    scheme.HandlerType = typeof(THandler);
                    scheme.DisplayName = displayName;
                });
            });
            if (configureOptions != null)
            {
                Services.Configure(authenticationScheme, configureOptions);
            }
            Services.AddTransient<THandler>();
            return this;
        }

照旧还是分为2个方法来进行调用,其重点就是AddSchemeHelper找个方法。其里面配置AuthenticationOptions类型。现在我们已经知道了IAuthenticationSchemeProvider何使注入的。还由AuthenticationSchemeProvider构造方法中IOptions<AuthenticationOptions> options是何使配置的,这样我们就对于认证有了一个初步的认识。现在可以知道对于认证中间件,必须要有一个IAuthenticationSchemeProvider 类型。而这个IAuthenticationSchemeProvider的实现类的构造函数必须要由IOptions<AuthenticationOptions> options,没有这两个类型,认证中间件应该是不会工作的。

回到认证中间件中。继续看var defaultAuthenticate = await Schemes.GetDefaultAuthenticateSchemeAsync();这句代码,源码如下

  public virtual Task<AuthenticationScheme> GetDefaultAuthenticateSchemeAsync()
            => _options.DefaultAuthenticateScheme != null
            ? GetSchemeAsync(_options.DefaultAuthenticateScheme)
            : GetDefaultSchemeAsync();


 public virtual Task<AuthenticationScheme> GetSchemeAsync(string name)
            => Task.FromResult(_schemes.ContainsKey(name) ? _schemes[name] : null);
  private Task<AuthenticationScheme> GetDefaultSchemeAsync()
            => _options.DefaultScheme != null
            ? GetSchemeAsync(_options.DefaultScheme)
: Task.FromResult
<AuthenticationScheme>(null);

 让我们先验证下方法1的三元表达式,应该执行那边呢?通过前面的代码我们知道AuthenticationOptions是在AuthenticationBuilder类型的AddSchemeHelper方法里面进行配置的。经过我的调试,发现方法1会走右边。其实最终还是从一个字典中取到了默认的AuthenticationScheme对象。到这里中间件的里面var defaultAuthenticate = await Schemes.GetDefaultAuthenticateSchemeAsync();代码就完了。最终就那到了AuthenticationScheme的对象。

下面来看看 中间件中var result = await context.AuthenticateAsync(defaultAuthenticate.Name);这句代码干了什么。按下F12发现是一个扩展方法,还是到HttpAbstractions解决方案里面找下源码

源码如下

 public static Task<AuthenticateResult> AuthenticateAsync(this HttpContext context, string scheme) =>
            context.RequestServices.GetRequiredService<IAuthenticationService>().AuthenticateAsync(context, scheme);

通过上面的方法,发现是通过IAuthenticationService的AuthenticateAsync() 来进行认证的。那么现在IAuthenticationService这个类是干什么 呢?

下面为IAuthenticationService的定义

 public interface IAuthenticationService
    {
               Task<AuthenticateResult> AuthenticateAsync(HttpContext context, string scheme);

               Task ChallengeAsync(HttpContext context, string scheme, AuthenticationProperties properties);

               Task ForbidAsync(HttpContext context, string scheme, AuthenticationProperties properties);

               Task SignInAsync(HttpContext context, string scheme, ClaimsPrincipal principal, AuthenticationProperties properties);

                Task SignOutAsync(HttpContext context, string scheme, AuthenticationProperties properties);
    }

 IAuthenticationService的AuthenticateAsync()方法的实现源码

public class AuthenticationService : IAuthenticationService
    {
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="schemes">The <see cref="IAuthenticationSchemeProvider"/>.</param>
        /// <param name="handlers">The <see cref="IAuthenticationRequestHandler"/>.</param>
        /// <param name="transform">The <see cref="IClaimsTransformation"/>.</param>
        public AuthenticationService(IAuthenticationSchemeProvider schemes, IAuthenticationHandlerProvider handlers, IClaimsTransformation transform)
        {
            Schemes = schemes;
            Handlers = handlers;
            Transform = transform;
        }
 public virtual async Task<AuthenticateResult> AuthenticateAsync(HttpContext context, string scheme)
        {
            if (scheme == null)
            {
                var defaultScheme = await Schemes.GetDefaultAuthenticateSchemeAsync();
                scheme = defaultScheme?.Name;
                if (scheme == null)
                {
                    throw new InvalidOperationException($"No authenticationScheme was specified, and there was no DefaultAuthenticateScheme found.");
                }
            }

            var handler = await Handlers.GetHandlerAsync(context, scheme);
            if (handler == null)
            {
                throw await CreateMissingHandlerException(scheme);
            }

            var result = await handler.AuthenticateAsync();
            if (result != null && result.Succeeded)
            {
                var transformed = await Transform.TransformAsync(result.Principal);
                return AuthenticateResult.Success(new AuthenticationTicket(transformed, result.Properties, result.Ticket.AuthenticationScheme));
            }
            return result;
        }
 

 通过构造方法可以看到这个类的构造方法需要IAuthenticationSchemeProvider类型和IAuthenticationHandlerProvider 类型,前面已经了解了IAuthenticationSchemeProvider是干什么的,取到配置的授权策略的名称,那现在IAuthenticationHandlerProvider 是干什么的,看名字感觉应该是取到具体授权策略的handler.废话补多少,看IAuthenticationHandlerProvider 接口定义把

 public interface IAuthenticationHandlerProvider
    {
        /// <summary>
        /// Returns the handler instance that will be used.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="authenticationScheme">The name of the authentication scheme being handled.</param>
        /// <returns>The handler instance.</returns>
        Task<IAuthenticationHandler> GetHandlerAsync(HttpContext context, string authenticationScheme);
    }

通过上面的源码,跟我猜想的不错,果然就是取得具体的授权策略

现在我就可以知道AuthenticationService是对IAuthenticationSchemeProvider和IAuthenticationHandlerProvider封装。最终调用IAuthentionHandel的AuthenticateAsync()方法进行认证。最终返回一个AuthenticateResult对象。

总结,对于asp.net core的认证来水,他需要下面这几个对象

AuthenticationBuilder      扶着对认证策略的配置与初始话

IAuthenticationHandlerProvider AuthenticationHandlerProvider 负责获取配置了的认证策略的名称

IAuthenticationSchemeProvider AuthenticationSchemeProvider 负责获取具体认证策略的handle

IAuthenticationService AuthenticationService 实对上面两个Provider 的封装,来提供一个具体处理认证的入口

IAuthenticationHandler 和的实现类,是以哦那个来处理具体的认证的,对不同认证策略的出来,全是依靠的它的AuthenticateAsync()方法。

AuthenticateResult  最终的认证结果。

哎写的太垃圾了。

 

 
反对 0举报 0 评论 0
 

免责声明:本文仅代表作者个人观点,与乐学笔记(本网)无关。其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
    本网站有部分内容均转载自其它媒体,转载目的在于传递更多信息,并不代表本网赞同其观点和对其真实性负责,若因作品内容、知识产权、版权和其他问题,请及时提供相关证明等材料并与我们留言联系,本网站将在规定时间内给予删除等相关处理.

  • 使用WebClient自动填写并提交ASP.NET页面表单的源代码
    使用WebClient自动填写并提交ASP.NET页面表单的
    转自:http://www.cnblogs.com/anjou/archive/2007/03/07/667253.html 在.NET中通过程序填写和提交表单还是比较简单。比如,要提交一个如下图所示的登录表单:           填写和提交以上表单的代码如下:       // 要提交表单的URI字符串
    02-09
  • asp.net mvc多条件+分页查询解决方案
    


            
asp.net mvc多条件+分页查询解决方案
    asp.net mvc多条件+分页查询解决方案
    http://www.cnblogs.com/nickppa/p/3232535.html开发环境vs2010css:bootstrapjs:jquery    bootstrap paginator原先只是想做个mvc的分页,但是一般的数据展现都需要检索条件,而且是多个条件,所以就变成了MVC多条件+分页查询因为美工不是很好,所以用的是
    02-09
  • ASP.NET操作Cookies的问题(Bug or Not)
    以下存和取都是在不同的页面中,如果是在同一个页面也没必要用cookies了。 Test1: 给Cookies赋值: const string AAA="aaa"; Response.Cookies[AAA].Value = "111;222;333"; 取值: string value = Request.Cookies[AAA].Value; // value为111 Test2: 给Cooki
    02-09
  • Asp.Net Core 自定义验证属性
      很多时候,在模型上的验证需要自己定义一些特定于我们需求的验证属性。所以这一篇我们就来介绍一下怎么自定义验证属性。  我们来实现一个验证邮箱域名的自定义验证属性,当然,最重要的是需要定义一个继承自ValidationAttribute的类,然后在实现其IsVal
    02-09
  • Asp.Net 之 枚举类型的下拉列表绑定
    有这样一个学科枚举类型:/// 学科 /// /summary public enum Subject {None = 0,[Description("语文")]Chinese = 1,[Description("数学")]Mathematics = 2,[Description("英语")]English = 3,[Description("政治")]Politics = 4,[Description("物理&qu
    02-09
  • [ASP.NET笔记] 1.Web基础知识
         1:http协议:     2:web服务器:     3:静态网页的概念     4:动态网页的概念       http协议:http(hypertext transfer protocol) 即超文本传输协议,这个协议是在internet上进行信息传送的协议任何网页之间要相互沟通,必须要尊循
    02-09
  • ASP.NET邮件发送 .net 发送邮件
      今天做了个ASP.NET做发送邮件功能,发现QQ邮箱好奇怪,当你用QQ邮箱做服务器的时候什么邮件都发送不出去(QQ邮箱除外)。而且爆出这样的错误:"邮箱不可用。 服务器响应为: Error: content rejected.http://mail.qq.com/zh_CN/help/content/rejectedmail.ht
    02-09
  • 由ASP.NET Core根据路径下载文件异常引发的探究
    前言    最近在开发新的项目,使用的是ASP.NET Core6.0版本的框架。由于项目中存在文件下载功能,没有使用类似MinIO或OSS之类的分布式文件系统,而是下载本地文件,也就是根据本地文件路径进行下载。这其中遇到了一个问题,是关于如何提供文件路径的,通
    02-09
  • ASP.NET的运行原理与运行机制 ASP.NET的开发模式包括
    ASP.NET的运行原理与运行机制 ASP.NET的开发模
    在Asp.net4和4.5中,新增了WebPages Framework,编写页面代码使用了新的Razor语法,代码更加的简洁和符合Web标准,编写方式更接近于PHP和以前的Asp,和使用WebForms这种模仿Windows Form编程方式有了很大不同,不再有大量控件和控件生成的大量不够灵活的代码
    02-09
  • ASP.NET 后台接收前台POST过来的json数据方法
     ASP.NET前后台交互之JSON数据 https://www.cnblogs.com/ensleep/p/3319756.html
    02-09
点击排行