首页 文章

反向代理背后的ASP.NET MVC应用程序 - 在auth之后使用错误的主机名

提问于
浏览
1

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

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进行硬编码,但这会产生错误,该路径应以/开头 .

1 回答

  • 0

    事实证明这很容易解决 . 我只是在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);
    };
    

相关问题