public class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationMode = AuthenticationMode.Active,
LoginPath = new PathString("/account/login"),
LogoutPath = new PathString("/account/logout"),
Provider = new CookieAuthenticationProvider
{
OnApplyRedirect = ApplyRedirect
},
});
}
private static void ApplyRedirect(CookieApplyRedirectContext context)
{
Uri absoluteUri;
if (Uri.TryCreate(context.RedirectUri, UriKind.Absolute, out absoluteUri))
{
var path = PathString.FromUriComponent(absoluteUri);
if (path == context.OwinContext.Request.PathBase + context.Options.LoginPath)
{
context.RedirectUri = "http://accounts.domain.com/login" +
new QueryString(
context.Options.ReturnUrlParameter,
context.Request.Uri.AbsoluteUri);
}
}
context.Response.Redirect(context.RedirectUri);
}
}
如果apps.domain.com是唯一可能的返回URL基数,您应该强烈考虑将context.Request.Uri.AbsoluteUri
替换为context.Request.PathBase + context.Request.Path + context.Request.QueryString
,并在您的身份验证服务器中构建一个绝对返回URL,以保护您的应用程序不受滥用重定向的影响.
希望这能有所帮助;)
EDIT:您可能会问自己,为什么我不使用context.RedirectUri
属性直接应用重定向.事实上,ICookieAuthenticationProvider.ApplyRedirect
负责多个重定向,与登录和注销流相对应(是的,我知道,它打破了单一责任原则……).但还有更糟糕的情况:context.RedirectUri
既可以表示身份验证端点在登录流开始时的绝对URL,也可以表示最终浏览器的目的地(即.真正的相对"返回URL"),当cookie被有效地发送回浏览器时…这就是为什么我们需要确保context.RedirectUri
是绝对的,并且对应于注册的context.Options.LoginPath
.