Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify CookieAuthenticationOptions LoginPath OnRedirectToReturnUrl Event

I have the following setup in my MVC 6 ASP.NET 5 project:

Startup.cs in the Configure Method:

app.UseCookieAuthentication(options =>
{
    options.AuthenticationScheme = "Cookie";
    options.LoginPath = new PathString("/<TENANT>/account/signin/");
    options.AccessDeniedPath = new PathString("/<TENANT>/account/unauthorised/");
    options.AutomaticAuthenticate = true;
    options.AutomaticChallenge = true;
    options.Events = new CookieAuthenticationEvents
    {
        OnRedirectToReturnUrl = MyClass.RedirectToReturnUrlAsync
    };
});

Events class:

public static class MyClass
{
    public static async Task RedirectToReturnUrlAsync(CookieRedirectContext context)
    {
        context.Options.LoginPath = new PathString("/<HERE I PLAN TO PUT LOGIC TO FIGURE OUT TENANT FROM CONTEXT>/account/signin");
    }

}

Lets say a user goes to the following url:

http://localhost/mycompany/securecontroller/secureaction

I want the Cookie middleware to redirect the user to:

http://localhost/mycompany/account/signin

The problem is the code "MyClass.RedirectToReturnUrlAsync" never gets hit when a Redirect to Return Url happens, so I cannot find the opportunity to modify the LoginPath at runtime.

I suspect I have something wrong in my setup. Has anybody ever encountered this problem?

Hooroo

like image 768
ZeroOne Avatar asked Apr 16 '16 11:04

ZeroOne


1 Answers

Ok, I think I figured it out. I was looking at the problem from the wrong angle (and after a getting some sleep!)

app.UseCookieAuthentication(options =>
{
    options.AuthenticationScheme = "Cookie";
    options.LoginPath = new PathString("/<TENANT>/account/signin/");
    options.AccessDeniedPath = new PathString("/<TENANT>/account/unauthorised/");
    options.AutomaticAuthenticate = true;
    options.AutomaticChallenge = true;
    options.Events = new MyCookieAuthenticationEvents();
});

The proper way to create your own custom Cookie Authentication Events would be to derive from the CookieAuthenticationEvents object and override the events you'd like to custom, something like this:

public class MyCookieAuthenticationEvents : CookieAuthenticationEvents
{
    public override Task RedirectToLogin(CookieRedirectContext context)
    {
        context.RedirectUri = <PUT LOGIC HERE TO REPLACE YOUR REDIRECT URI>
        return base.RedirectToLogin(context);
    }
}

I was also targeting the wrong Event in my previous attempt. In my case, the correct method to override was the "RedirectToLogin" method.

Hooroo

like image 61
ZeroOne Avatar answered Sep 30 '22 12:09

ZeroOne