【问题标题】:How to request authentication from custom middleware in ASP.NET Core 2.0如何从 ASP.NET Core 2.0 中的自定义中间件请求身份验证
【发布时间】:2018-10-21 18:41:09
【问题描述】:

我有两个自定义 ASP.NET Core 中间件:一个用于身份验证(注册自己的身份验证方案),另一个用于某些业务工作。

如何在另一个中间件中使用身份验证中间件?我可以在这样的 MVC 中轻松使用身份验证:

 services.AddMvc(config =>
 {
     var policy = new AuthorizationPolicyBuilder()
                      .RequireAuthenticatedUser()
                      .Build();
     config.Filters.Add(new AuthorizeFilter(policy));
 });

我还可以提供我自己的AuthenticationSchemeProvider 以根据请求的 URL 使用不同的身份验证方案。但身份验证中间件仅适用于 MVC 控制器。我希望它在我的自定义中间件运行之前也运行。有可能吗?

【问题讨论】:

标签: c# asp.net-core asp.net-core-middleware


【解决方案1】:

在自定义中间件方法Invoke() 调用ChallengeAsync() 如果用户未通过身份验证:

public async Task Invoke(HttpContext httpContext, IServiceProvider serviceProvider)
{
    if (!httpContext.User.Identity.IsAuthenticated)
    {
        await httpContext.ChallengeAsync();
    }
    else { /* logic here */ }
}

必须添加 NuGet 包 Microsoft.AspNetCore.Authentication.Abstractions

以上代码将运行默认的身份验证服务来对用户进行身份验证。如果默认的是您的自定义身份验证中间件,那么它将被调用。

【讨论】:

  • 等待 httpContext.ChallengeAsync();很有帮助。但是 httpContext.User.Identity.IsAuthenticated 总是假的
  • @FemilShajin 您可能需要添加对 context.Request.Path 的检查,具体取决于您使用的身份验证提供程序。有关示例,请参见 stackoverflow.com/questions/53088514/…
【解决方案2】:

这是基于Rython使用Windows身份验证的具体情况的回答,但也允许设计的控制器使用其他类型的身份验证:

/// <summary>
/// checks if current request resource can be accesses without being Windows-authenticated
/// </summary>
/// <param name="context">http context</param>
/// <returns>true if non-Windows is allowed. Otherwise, false</returns>
public static bool IsAllowedWithoutWindowsAuth(HttpContext context)
{
    bool isAllowedWithoutWindowsAuth = context.Request.Method == "OPTIONS" ||
                                       AllowedControllers.Any(c =>
                                       {
                                           string path = context.Request.Path.ToString();
                                           return path.StartsWith(c, StringComparison.InvariantCulture);
                                       });
    return isAllowedWithoutWindowsAuth;
}

// custom middleware code 
public async Task Invoke(HttpContext context)
{
    // anonymous path, skipping
    if (IsAllowedWithoutWindowsAuth(context))
    {
        await _next(context);
        return;
    }

    if (!context.User.Identity.IsAuthenticated)
    {
        await context.ChallengeAsync("Windows");
        return;
    }

    // other code here
    await _next(context);
 }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-30
    • 2018-07-19
    • 2016-07-05
    • 1970-01-01
    • 2017-02-15
    • 2018-02-24
    相关资源
    最近更新 更多