tnblog
首页
视频
资源
登录
什么时候才能领悟,取之越多失之越多
排名
6
文章
6
粉丝
16
评论
8
{{item.articleTitle}}
{{item.blogName}} : {{item.content}}
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2024TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
公网安备:50010702506256
欢迎加群交流技术

identity server4身份验证中间件源码

5073人阅读 2020/1/17 10:48 总访问:1084532 评论:0 收藏:0 手机
分类: .net core

通过下载ids4的源码来看,可以把相关的源码放到自己项目中,方便分析整个流程和进行一些个性化定制,下面贴一下身份验证中间件的源码


扩展方法:

 public static class MyAuthAppBuilderExtensions
    {
        public static IApplicationBuilder UseMyAuthentication(this IApplicationBuilder app)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }

            return app.UseMiddleware<MyAuthenticationMiddleware>();
        }
    }

具体中间件的类:

public class MyAuthenticationMiddleware
    {
        private readonly RequestDelegate _next;

        public MyAuthenticationMiddleware(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;
                bool issccuess = await handler.HandleRequestAsync();
                if (handler != null && issccuess)
                {
                    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);
        }
    }


欢迎加群讨论技术,群:677373950(满了,可以加,但通过不了),2群:656732739

评价