identity server4身份验证中间件源码
电脑版发表于:2020/1/17 10:48
通过下载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); } }