Prevent redirect to requested page after authentication - Always send to callback URL

I have an MVC application setup as a regular web application in my tenant.
This is using standard database email/password for authentication within Auth0.
I am using the UseOpenIdConnectAuthentication and have the RedirectUri for this set to the page I want to direct users to after login/authentication.

If a user requests a page that requires authentication, they are sent to the Auth0 login page but after authentication they continue to the page they originally requested without hitting my callback/redirect url.

For example say a user tries to visit https://DomainName/MySecretPage instead of https://DomainName, after login they are taken straight to this page instead of my callback/redirect url (e.g. https://DomainName/WelcomePage). If they visit https://DomainName after login/authentication they are successfully sent to the callback/redirect url (e.g. https://DomainName/WelcomePage).

Is it possible to prevent this as I want all users to hit the callback/redirect url on login/authentication? Or alternatively force all users (via a rule maybe) to visit the callback/redirect url?

Thanks,
Peter

The behavior you want to avoid is frequently the end goal so I believe it’s likely that the configuration you are using is coded in such way to guarantee that the end-user is ultimately redirected to the original page you requested.

The above is usually done by dynamically including that original URL as part of the authentication request state so that when a login is completed that information is available and the application redirects again to the original page.

Given that you are not interested in that behavior you would likely need to remove the logic that dynamically add the original URL or even just hardcode your own URL instead of using a dynamic one. For example, for OWIN MVC sample that behavior is achieved by this line (auth0-aspnet-owin-mvc-samples/AccountController.cs at master · auth0-samples/auth0-aspnet-owin-mvc-samples · GitHub) which uses the return URL parameter to keep track of that original URL being accessed. You should be able to tweak that logic to have the behavior you desire in terms of final redirect.

Hi @jmangelo.

Thanks for taking a look at this. I had already changed the code you suggested in my MVC project to go directly to the page:

 public ActionResult Login()
    {
        HttpContext.GetOwinContext().Authentication.Challenge(new AuthenticationProperties
        {
            RedirectUri = Url.Action("<URLIWantUsersToBeDirectedToHere>")
        },
            "Auth0");

        return new HttpUnauthorizedResult();
    }

However in the scenario I described in my original post this Login function is not called after Auth0 authentication.

In my list of Allowed Callback URLs I have both the Login action URL and the URL of the page I want user to be directed to after authentication.

I should also mention I am using the new Universal Login page.

Can you share a bit more about the configuration you’re using for UseOpenIdConnectAuthentication and ideally, an HAR file (after redacting sensitive information) of a login that ends up in the incorrect page.

Hi @jmangelo

I have attached a file containing some of the code that runs on site startup (this is probably almost identical to the code in the starter project you referenced).

StartupAuthConfig.txt (3.4 KB)

I have also attached a HAR file showing it hitting my callback (http://localhost:60123/Account/LoadUserAccountIdentity) but redirecting without running the code for callback.

localhost.har (2.0 MB)

Hi @jmangelo.

I have just downloaded and modified the Authorization quickstart project (auth0-aspnet-owin-mvc-samples/Quickstart/03-Authorization at master · auth0-samples/auth0-aspnet-owin-mvc-samples · GitHub), as per your earlier suggestion regarding setting the RedirectUri in Login method to a static method.

public ActionResult Login(string returnUrl)
    {
        HttpContext.GetOwinContext().Authentication.Challenge(new AuthenticationProperties
            {
                RedirectUri = Url.Action("Index", "Home")
            },
            "Auth0");
        return new HttpUnauthorizedResult();
    }

I am seeing the same issue with this project. If I try to browse to http://localhost:3000/Account/UserProfile when I am not logged in, after authenticating it takes me straight to http://localhost:3000/Account/UserProfile instead of my redirect page.

For anyone else looking to resolve this I was able to prevent redirection to page requested by user after authentication by adding the following to the Notifications property of the OpenIdConnectAuthenticationOptions:

SecurityTokenValidated = (context) =>
                {
                    context.AuthenticationTicket.Properties.RedirectUri = auth0RedirectUri;
                    return Task.FromResult(0);
                },

I believe that this changes the redirect URI at point of authentication to my Auth0 callback URI. So instead of redirecting to page user requested they are redirected to my callback. Note this is in addition to the change @jmangelo already mentioned in the Login function.

So my full code for configuring OpenIdConnectAuthentication is as follows:

app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
        {
            AuthenticationType = "Auth0",

            Authority = $"https://{auth0Domain}",

            ClientId = auth0ClientId,
            ClientSecret = auth0ClientSecret,

            RedirectUri = auth0RedirectUri,
            PostLogoutRedirectUri = auth0PostLogoutRedirectUri,

            ResponseType = OpenIdConnectResponseType.CodeIdToken,
            Scope = "openid profile",

            TokenValidationParameters = new TokenValidationParameters
            {
                NameClaimType = "name"
            },

            Notifications = new OpenIdConnectAuthenticationNotifications
            {
                SecurityTokenValidated = (context) =>
                {
                    context.AuthenticationTicket.Properties.RedirectUri = auth0RedirectUri;
                    return Task.FromResult(0);
                },

                RedirectToIdentityProvider = (notification) =>
                        {
                            if (notification.ProtocolMessage.RequestType == OpenIdConnectRequestType.Logout)
                            {
                                var logoutUri = $"https://{auth0Domain}/v2/logout?client_id={auth0ClientId}";

                                var postLogoutUri = notification.ProtocolMessage.PostLogoutRedirectUri;
                                if (!string.IsNullOrEmpty(postLogoutUri))
                                {
                                    if (postLogoutUri.StartsWith("/"))
                                    {
                                // transform to absolute
                                var request = notification.Request;
                                        postLogoutUri = request.Scheme + "://" + request.Host + request.PathBase + postLogoutUri;
                                    }
                                    logoutUri += $"&returnTo={ Uri.EscapeDataString(postLogoutUri)}";
                                }

                                notification.Response.Redirect(logoutUri);
                                notification.HandleResponse();
                            }

                            return Task.FromResult(0);
                        }
            }
        });

If anyone can see any issues with this solution/implementation please let me know. Cheers

1 Like

Thanks for posting your solution; yesterday I got diverted to other things and was unable to review your replies.

1 Like

This topic was automatically closed 15 days after the last reply. New replies are no longer allowed.