[英]ASP.NET MVC application behind reverse proxy - using wrong host name after auth
I have an ASP.NET MVC application using OWIN authentication that is running behind a reverse proxy.我有一个使用 OWIN 身份验证的 ASP.NET MVC 应用程序,它在反向代理后面运行。
The authentication in ASP.NET is set up like this: 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))
}
});
The reverse proxy in iis is setup like this in the web.config: 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>
The reverse proxy is hosted at https://www.mydomain.toplevel/app/ {R:1}反向代理托管在https://www.mydomain.toplevel/app/ {R:1}
Everything is working fine, RedirectToAction will redirect to www.mydomain.toplevel.一切正常,RedirectToAction 将重定向到 www.mydomain.toplevel。
But when I try to open a controller with the AuthenticationAttribute, the redirect will go to https://myapp.mydomain.toplevel/account/login instead of www.mydomain.toplevel但是当我尝试使用 AuthenticationAttribute 打开控制器时,重定向将转到https://myapp.mydomain.toplevel/account/login而不是 www.mydomain.toplevel
How can I configure this that my application stays behind the reverse proxy, even when the auth redirect is happening?我如何配置我的应用程序保持在反向代理之后,即使正在发生身份验证重定向? As a first workaround, I tried to hardcode the LoginPath with the hostname in front, but this will give an error that the path should start with a /.
作为第一个解决方法,我尝试使用前面的主机名对 LoginPath 进行硬编码,但这将给出路径应以 / 开头的错误。
Turns out this is quite easy to fix.事实证明,这很容易解决。 I just implemented my own OnApplyRedirect method on the AuthenticationProvider:
我刚刚在 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);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.