2017-09-28 36 views
4

在ASP.NET 1.x的核心,我可以使用的身份验证方法配置但现在在ASP.NET核2.0我在设置应有尽有ConfigureServices并且不能配置它在配置方法。例如如何ConfigureServices验证在ASP.NET核心基于路线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()); 

回答

5

在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容器(理想情况下进行注册,作为一个单身):

services.AddSingleton<IAuthenticationSchemeProvider, CustomAuthenticationSchemeProvider>();