我最终定义了一个基于的简单中间件 https://github.com/aspnet/Security/issues/1469#issuecomment-334982498
app.Use(async (context, next) => { var authHeader = AuthenticationHeaderValue.Parse(context.Request.Headers[HeaderNames.Authorization]); var schemeName = authHeader?.Scheme ?? string.Empty; var provider = context.RequestServices.GetService<IAuthenticationSchemeProvider>(); var scheme = await provider.GetSchemeAsync(schemeName); if (scheme != null) { var result = await context.AuthenticateAsync(scheme.Name); if (result.Succeeded) { context.User = result.Principal; } } await next.Invoke(); });
从2.1开始,可以添加自定义方案策略并使用转发默认方案 AuthenticationSchemeOptions.ForwardDefaultSelector ,见: https://github.com/aspnet/Security/issues/1469#issuecomment-399239254
AuthenticationSchemeOptions.ForwardDefaultSelector