MVC Owin Cookie Authentication - Override ReturnUrl Generation

笑着哭i 提交于 2019-12-01 23:18:25

Looks like I figured it out: I altered my startup config as follows:

    public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Security/Login"),
            CookieSecure = CookieSecureOption.SameAsRequest,
            SlidingExpiration = true,
            CookieName = "Program.Auth",
            ExpireTimeSpan = TimeSpan.FromSeconds(15)/*FromHours(1)*/,
            Provider = new CookieAuthenticationProvider { OnApplyRedirect = CustomRedirect }
        });

        // TODO - Figure out what claims type to base this on.
        AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.Email;
    }

    private static void CustomRedirect(CookieApplyRedirectContext context)
    {
        var redirectUrl = context.Options.LoginPath.ToString();
        if (context.Request.Method == WebRequestMethods.Http.Get)
        {
            var returnUrl = context.Request.Path.ToString();
            if (!string.IsNullOrEmpty(returnUrl) && !returnUrl.Equals("/"))
                redirectUrl += "?" + context.Options.ReturnUrlParameter + "=" + returnUrl;
        }
        else if (context.Request.Method == WebRequestMethods.Http.Post)
        {
            //TODO: add toastr message showing that the post did not succeed
        }
        context.Response.Redirect(redirectUrl + "?tbn=inactive");
    }
}

Now I only get a ReturnUrl for GET requests. I tested with PathAndQuery but so far it has been causing other problems. For the moment, I would say the main problem here is solved.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!