在 ASP.NET Core 1.x 中,我可以在 中使用身份验证方法配置 但现在在 ASP.NET Core 2.0 中,我必须在 中设置所有内容配置服务 并且无法在 中配置它配置 方法。例如
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication()
.AddCookie()
.AddXX();
}
然后在
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
....
app.UseAuthentication();
}
过去,我可以使用类似的东西
app.UseOpenIdConnectAuthentication();
我不能再像这样配置它了。
那么我现在如何在 ASP.NET Core 2.0 中使用这样的东西?
app.Map(new PathString("/MyPath"), i => i.UseMyAuthMethod());
最佳答案
在 2.0 中,进行每条路由身份验证的最佳选择是使用自定义 IAuthenticationSchemeProvider
:
public class CustomAuthenticationSchemeProvider : AuthenticationSchemeProvider
{
private readonly IHttpContextAccessor httpContextAccessor;
public CustomAuthenticationSchemeProvider(
IHttpContextAccessor httpContextAccessor,
IOptions<AuthenticationOptions> options)
: base(options)
{
this.httpContextAccessor = httpContextAccessor;
}
private async Task<AuthenticationScheme> GetRequestSchemeAsync()
{
var request = httpContextAccessor.HttpContext?.Request;
if (request == null)
{
throw new ArgumentNullException("The HTTP request cannot be retrieved.");
}
// For API requests, use authentication tokens.
if (request.Path.StartsWithSegments("/api"))
{
return await GetSchemeAsync(OAuthValidationDefaults.AuthenticationScheme);
}
// For the other requests, return null to let the base methods
// decide what's the best scheme based on the default schemes
// configured in the global authentication options.
return null;
}
public override async Task<AuthenticationScheme> GetDefaultAuthenticateSchemeAsync() =>
await GetRequestSchemeAsync() ??
await base.GetDefaultAuthenticateSchemeAsync();
public override async Task<AuthenticationScheme> GetDefaultChallengeSchemeAsync() =>
await GetRequestSchemeAsync() ??
await base.GetDefaultChallengeSchemeAsync();
public override async Task<AuthenticationScheme> GetDefaultForbidSchemeAsync() =>
await GetRequestSchemeAsync() ??
await base.GetDefaultForbidSchemeAsync();
public override async Task<AuthenticationScheme> GetDefaultSignInSchemeAsync() =>
await GetRequestSchemeAsync() ??
await base.GetDefaultSignInSchemeAsync();
public override async Task<AuthenticationScheme> GetDefaultSignOutSchemeAsync() =>
await GetRequestSchemeAsync() ??
await base.GetDefaultSignOutSchemeAsync();
}
不要忘记在 DI 容器中注册它(理想情况下,作为单例):
// IHttpContextAccessor is not registered by default
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddSingleton<IAuthenticationSchemeProvider, CustomAuthenticationSchemeProvider>();
关于authentication - 如何在 ASP.NET Core 2.0 中配置基于路由的服务身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46464469/