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);
}
}
If apps.domain.com is the only return URL base possible, you should strongly consider replacing context.Request.Uri.AbsoluteUri
with context.Request.PathBase + context.Request.Path + context.Request.QueryString
and build an absolute return URL in your authentication server to protect your apps from abusive redirects.
Hope this helps 😉
EDIT: you might ask yourself why I don’t directly apply the redirect using the context.RedirectUri
property. In fact, ICookieAuthenticationProvider.ApplyRedirect
is responsible of multiple redirects, corresponding to the log-in and log-out flows (yep, I know, it breaks the single responsibility principle…). But there’s even worse: context.RedirectUri
can either represent the authentication endpoint’s absolute URL in the beginning of the log-in flow or the final browser’s destination (ie. the real relative “return URL”) when the cookie is effectively being sent back to the browser… that’s why we need to make sure that context.RedirectUri
is absolute and corresponds to the registered context.Options.LoginPath
.