aspnetcore 认证相关类简要说明三

今天我们再来了解一个很重要的接口IAuthenticationService的实现类AuthenticationService:

public class AuthenticationService : IAuthenticationService
{
        public AuthenticationService(IAuthenticationSchemeProvider schemes, IAuthenticationHandlerProvider handlers, IClaimsTransformation transform)
        {
            Schemes = schemes;
            Handlers = handlers;
            Transform = transform;
        }

        public IAuthenticationSchemeProvider Schemes { get; }
        public IAuthenticationHandlerProvider Handlers { get; }
        public IClaimsTransformation Transform { get; }

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

        /// <summary>
        /// Challenge the specified authentication scheme.
        /// </summary>
        /// <param name="context">The <see cref="HttpContext"/>.</param>
        /// <param name="scheme">The name of the authentication scheme.</param>
        /// <param name="properties">The <see cref="AuthenticationProperties"/>.</param>
        /// <returns>A task.</returns>
        public virtual async Task ChallengeAsync(HttpContext context, string scheme, AuthenticationProperties properties)
        {
            if (scheme == null)
            {
                var defaultChallengeScheme = await Schemes.GetDefaultChallengeSchemeAsync();
                scheme = defaultChallengeScheme?.Name;
                if (scheme == null)
                {
                    throw new InvalidOperationException($"No authenticationScheme was specified, and there was no DefaultChallengeScheme found.");
                }
            }

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

            await handler.ChallengeAsync(properties);
        }

        /// <summary>
        /// Forbid the specified authentication scheme.
        /// </summary>
        public virtual async Task ForbidAsync(HttpContext context, string scheme, AuthenticationProperties properties)
        {
            if (scheme == null)
            {
                var defaultForbidScheme = await Schemes.GetDefaultForbidSchemeAsync();
                scheme = defaultForbidScheme?.Name;
                ...
            }

            var handler = await Handlers.GetHandlerAsync(context, scheme);       ...await handler.ForbidAsync(properties);
        }

        /// <summary>
        /// Sign a principal in for the specified authentication scheme.
        /// </summary>
        public virtual async Task SignInAsync(HttpContext context, string scheme, ClaimsPrincipal principal, AuthenticationProperties properties)
        {       ...if (scheme == null)
            {
                var defaultScheme = await Schemes.GetDefaultSignInSchemeAsync();
                scheme = defaultScheme?.Name;
                ...
            }

            var handler = await Handlers.GetHandlerAsync(context, scheme);
            ...var signInHandler = handler as IAuthenticationSignInHandler;
            ...await signInHandler.SignInAsync(principal, properties);
        }

        /// <summary>
        /// Sign out the specified authentication scheme.
        /// </summary>
        public virtual async Task SignOutAsync(HttpContext context, string scheme, AuthenticationProperties properties)
        {
            if (scheme == null)
            {
                var defaultScheme = await Schemes.GetDefaultSignOutSchemeAsync();
                scheme = defaultScheme?.Name;
                if (scheme == null)
                {
                    throw new InvalidOperationException($"No authenticationScheme was specified, and there was no DefaultSignOutScheme found.");
                }
            }

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

            var signOutHandler = handler as IAuthenticationSignOutHandler;
            if (signOutHandler == null)
            {
                throw await CreateMismatchedSignOutHandlerException(scheme, handler);
            }

            await signOutHandler.SignOutAsync(properties);
        }}

该类通过构造方法,将我们两篇中讲到了IAuthenticationSchemeProvider和IAuthenticationHandlerProvider注入了进来,第三个参数不是很重要就飘过了。拉下来我们看看它的这几个方法AuthenticateAsync、ChallengeAsync、ForbidAsync、SignInAsync和SignOutAsync等方法,他们的套路几乎都一样的,通过注入进来的两个接口的实例,最终获得到IAuthenticationHandler接口实例的同名方法。

关于IAuthenticationService、IAuthenticationHandlerProvider和IAuthenticationSchemeProvider我们又是什么时候注入到服务容器里去的呢?它是在AuthenticationCoreServiceCollectionExtensions这个静态类中的AddAuthenticationCore扩展方法注入到容器中的:

    public static class AuthenticationCoreServiceCollectionExtensions
    {
        public static IServiceCollection AddAuthenticationCore(this IServiceCollection 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;
        }

        public static IServiceCollection AddAuthenticationCore(this IServiceCollection services, Action<AuthenticationOptions> configureOptions) {
            ...
            services.AddAuthenticationCore();
            services.Configure(configureOptions);
            return services;
        }
    }

该扩展方法是在Startup的ConfigureServices方法调用的。这个就不贴代码了。

注入完以后呢?怎么使用呢?为了方便使用,aspnetcore为我们在外面又裹了一层,那就是AuthenticationHttpContextExtensions为HttpContext添加的扩展方法。我们可以在Controller如下调用:

public class HomeController : Controller
{
        public IActionResult Index()
        {
            var result = HttpContext.AuthenticateAsync();
            return View(result.Result);
        }
}

至此认证相关的核心元素介绍完成,本篇到此结束。

原文地址:https://www.cnblogs.com/koeltp/p/9886651.html

时间: 2024-10-10 23:28:20

aspnetcore 认证相关类简要说明三的相关文章

aspnetcore 认证相关类简要说明二

能过<aspnetcore 认证相关类简要说明一>我们已经了解如何将AuthenticationOptions注入到我们依赖注入系统.接下来,我们将了解一下IAuthenticationSchemeProvider通过AuthenticationOptions如何提供AuthenticationScheme的.aspnetcore 中IAuthenticationSchemeProvider默认实现是AuthenticationSchemeProvider,我们简单的分析下它的源码(以下是我简

hive认证相关类分析

目前的hive版本是支持authentication和authorization的(再加上计费就是3A了,哈哈), 在hive的java.org.apache.hadoop.hive.conf.HiveConf类中定义的权限相关的设置项有: HIVE_AUTHORIZATION_ENABLED("hive.security.authorization.enabled", false),   //是否开启权限验证 HIVE_AUTHORIZATION_MANAGER("hive

iOS开发RunLoop学习:三:Runloop相关类(source和Observer)

一:RunLoop相关类: 其中:source0指的是非基于端口por,说白了也就是处理触摸事件,selector事件,source1指的是基于端口的port:是处理系统的一些事件 注意:创建一个RunLoop之后,有默认的运行模式mode,也可以为RunLoop指定运行模式,RunLoop启动必须得有运行模式,而且在运行模式中必须还有timer或是source事件其中之一,否则RunLoop就会退出.启动RunLoop必须调用start方法 二:RunLoop运行处理逻辑 RunLoop通知观

三、Java基础工具(1)_常用类——数学相关类

2018-05-13 数学相关类 一.Math类 Java 的 Math 包含了用于执行基本数学运算的属性和方法,如初等指数.对数.平方根和三角函数.   Math 的方法都被定义为 static 形式,通过 Math 类可以在主函数中直接调用 参考:https://blog.csdn.net/tomorrowtodie/article/details/52590688 ---------------------------------------------------------------

saltstack管理三之saltstack认证相关

saltstack认证相关 认证过程: 当初始化安装minion,minion服务启动后minion端会生成一个密钥对,并产生一个ID值,minion服务会安装ID值命名的公钥发送给master,直到接受为止; [[email protected] minion]# pwd /etc/salt/pki/minion [[email protected] minion]# ls minion.pem  minion.pub 注意:刚安装完minion,未启动时,pki目录是不存在的 启动minio

Web---演示Servlet的相关类、下载技术、线程问题、自定义404页面

Servlet的其他相关类: ServletConfig – 代表Servlet的初始化配置参数. ServletContext – 代表整个Web项目. ServletRequest – 代表用户的请求. ServletResponse – 代表用户的响应. HttpSession – 代表用户的一次会话. 本篇博客演示:ServletConfig类 和 ServletContext 类(网页点击量统计,留言板和图片下载技术(其他类型文件类似)) ServletConfig: 它包含了Serv

Android 网络编程 API笔记 - java.net 包 权限 地址 套接字 相关类 简介

Android 网络编程相关的包 : 9 包, 20 接口, 103 类, 6 枚举, 14异常; -- Java包 : java.net 包 (6接口, 34类, 2枚举, 12异常); -- Android包 : android.net 包 (1接口, 19类, 3枚举, 1异常), android.net.http 包 (6类), android.net.nsd 包 (3接口, 2类), android.net.rtp (4类), android.net.sip 包 (1接口, 9类, 1

聊聊高并发(二十)解析java.util.concurrent各个组件(二) 12个原子变量相关类

这篇说说java.util.concurrent.atomic包里的类,总共12个.网上有非常多文章解析这几个类.这里挑些重点说说. 这12个类能够分为三组: 1. 普通类型的原子变量 2. 数组类型的原子变量 3. 域更新器 普通类型的原子变量的6个, 1. 当中AtomicBoolean, AtomicInteger, AtomicLong, AtomicReference分别相应boolean, int,  long, object完毕主要的原子操作 2. AtomicMarkableRe

RecipientEditTextView相关类

概述 RecipientEditTextView是Android原生短信和电子邮件中用到的控件,代码位于frameworks/opt/chips(mtk代码中有对其修改,位于frameworks/ex/chips),会编译成libchips的jar包,app在编译时把它作为静态库编译. 如图所示,其中有"+10"字样的所在行就是RecipientEditTextView控件.每个号码有对应联系人的话会显示相应头像和名称,图像为一个圆角矩形,代码中对应的数据机构为一个chip.10表示已