是否可以允许匿名访问Windows身份验证中的某些页面?

时间:2018-03-30 05:09:55

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

我正在尝试在Asp.net core 2.0中实现Windows身份验证。 在这里我已经完成了Windows身份验证,只需在创建解决方案时选择 Windows身份验证选项, 但是在这里我想制作一些页面公开可用,为此我尝试了类似下面的代码,这些代码无效。

[Authorize(Roles = "Administrator")]
public IActionResult Index()
    {
        return View();
    }

 [AllowAnonymous]
 public IActionResult About()
    {
        ViewData["Message"] = "Your application description page.";

        return View();
    }

那么是否可以在Windows身份验证中公开访问某些页面?

1 个答案:

答案 0 :(得分:0)

是的,有可能。这就是我设法在ASP.NET Core 2.0.x中做到这一点的方式(不确定它是否在ASP.NET Core 1.x中工作)。

1。创建一个中间件,以区分使用Windows身份验证的控制器和不使用Windows身份验证的控制器

/// <summary>
/// a middleware that allows that some requests to bypass Windows authentication
/// </summary>
public class NtlmAndAnonymousSetupMiddleware
{
    #region Variables
    private readonly RequestDelegate _next;

    //TODO: maybe this can be improved to get rid of these magic strings
    private List<string> AllowedControllers = new List<string>
    {
        "/Anonymous",
        "/swagger"
    };
    #endregion

    /// <summary>
    /// 
    /// </summary>
    /// <param name="next"></param>
    public NtlmAndAnonymousSetupMiddleware(RequestDelegate next)
    {
        this._next = next;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    public async Task Invoke(HttpContext context)
    {
        // if requests target anonymous controller or there is a CORS related OPTIONS request
        // => let it be and challenge only for other request methods (GET, POST etc.)
        if (context.User.Identity.IsAuthenticated ||
            context.Request.Method == "OPTIONS" ||
            AllowedControllers.Any(c =>
            {
                string path = context.Request.Path.ToString();
                return path.StartsWith(c, StringComparison.InvariantCulture);
            }))
        {
            await _next(context);
            return;
        }

        await context.ChallengeAsync("Windows");
    }

}

一种特殊情况是,当接收到不能满足Windows身份验证挑战的OPTIONS请求(与CORS相关)时。

2。在Startup.cs中注册中间件

/// <summary>
/// allow anonymous requests (that are handled by application afterwards)
/// </summary>
/// <param name="app"></param>
protected virtual void AllowAnonymous(IApplicationBuilder app)
{
    app.UseMiddleware<NtlmAndAnonymousSetupMiddleware>();
}

public void Configure(IApplicationBuilder app)
{
    AllowAnonymous(app);
    // ...
}

3。允许在IIS中进行匿名身份验证

当然,Web应用程序应配置为还允许匿名身份验证(Windows身份验证除外)

注意:指的是web.config,我不记得ASP.NET Core 1.x是否要求这样做,但是在IIS中托管时我总是使用它:

<configuration>
  <system.webServer>
    <handlers> 
      <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
    </handlers>
    <aspNetCore processPath="dotnet" arguments=".\TheApp.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="true" /> 
  </system.webServer>
</configuration>