ASP.NET 反向代理背后的 MVC 应用程序 - 身份验证后使用了错误的主机名

ASP.NET MVC application behind reverse proxy - using wrong host name after auth

我有一个 ASP.NET MVC 应用程序使用 OWIN 身份验证 运行 在反向代理后面。

ASP.NET中的认证设置如下:

        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,

            LoginPath = new PathString("/Account/Login"),
            Provider = new CookieAuthenticationProvider
            {
                // Enables the application to validate the security stamp when the user logs in.
                // This is a security feature which is used when you change a password or add an external login to your account.  
                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                    validateInterval: TimeSpan.FromMinutes(30),
                    regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
            }
        });

iis 中的反向代理在 web.config:

中是这样设置的
<system.webServer>
<httpErrors errorMode="Detailed" />
<asp scriptErrorSentToBrowser="true"/>
    <rewrite>
            <rule name="proxy" stopProcessing="true">
                <match url="^app/?(.*)" />
                <serverVariables>
                    <set name="X_REQUESTED_URL_PATH" value="{R:1}" />
                </serverVariables>
                <action type="Rewrite" url="https://myapp.mydomain.toplevel/app/{R:1}" />
            </rule>
    </rewrite>
<system.webServer>

反向代理托管在 https://www.mydomain.toplevel/app/{R:1}

一切正常,RedirectToAction 将重定向到 www.mydomain.toplevel。

但是当我尝试使用 AuthenticationAttribute 打开控制器时,重定向将转到 https://myapp.mydomain.toplevel/account/login 而不是 www.mydomain.toplevel

如何配置我的应用程序保持在反向代理之后,即使在进行身份验证重定向时也是如此?作为第一个解决方法,我尝试使用前面的主机名对 LoginPath 进行硬编码,但这会给出路径应以 /.

开头的错误

原来这很容易解决。我刚刚在 AuthenticationProvider 上实现了我自己的 OnApplyRedirect 方法:

var provider = new CookieAuthenticationProvider
{
    // ..
};

provider.OnApplyRedirect = context =>
{
    UrlHelper _url = new UrlHelper(System.Web.HttpContext.Current.Request.RequestContext);
    String actionUri = _url.Action("Login", "Account", new { ReturnUrl = context.Request.Uri.PathAndQuery });
    context.Response.Redirect(actionUri);
};