如何根据ASP.NET Core 2.0中的路由配置服务身份验证

时间:2017-09-28 08:30:49

标签: authentication asp.net-core asp.net-core-mvc

在ASP.NET Core 1.x中,我可以在 配置 中使用身份验证方法,但现在在ASP.NET Core 2.0中,我必须在 <中设置所有内容em> ConfigureServices ,无法在 配置 方法中对其进行配置。例如

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 :(得分:18)

在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>();

答案 1 :(得分:2)

Microsoft docs说出要在ASP.NET Core 2+中使用多种身份验证方案的操作:

  

以下示例启用了对每个方案的动态选择方案   请求依据。也就是说,如何混合Cookie和API身份验证:

if tableViewData[indexPath.row].opened == true {

}

示例:

我必须实现一个混合身份验证解决方案,其中对于某些请求我需要Cookie身份验证,而对于其他请求则需要令牌身份验证。这就是我的样子:

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddCookie(options =>
        {
            // For example, can foward any requests that start with /api 
            // to the api scheme.
            options.ForwardDefaultSelector = ctx => 
               ctx.Request.Path.StartsWithSegments("/api") ? "Api" : null;
        })
        .AddYourApiAuth("Api");
}

其中JWT承载身份验证实现为described in this answer

提示:

对我来说,最大的“陷阱”之一是:即使services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(options => { // if URL path starts with "/api" then use Bearer authentication instead options.ForwardDefaultSelector = httpContext => httpContext.Request.Path.StartsWithSegments("/api") ? JwtBearerDefaults.AuthenticationScheme : null; }) .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, o => { o.TokenValidationParameters.ValidateIssuerSigningKey = true; o.TokenValidationParameters.IssuerSigningKey = symmetricKey; o.TokenValidationParameters.ValidAudience = JwtSignInHandler.TokenAudience; o.TokenValidationParameters.ValidIssuer = JwtSignInHandler.TokenIssuer; }); 策略将以“ / api”开头的URL的请求转发到Cookies策略,经cookie身份验证的用户仍可以如果您使用的是Bearer批注,仍然可以访问这些URL。如果希望仅通过[Authorize]身份验证访问这些URL,则必须在API控制器/操作上使用Bearer批注。