Search code examples
asp.net-mvcasp.net-mvc-3model-view-controllerasp.net-mvc-routing

MVC Core 3.0 options.LoginPath - add localization route parameter


I have the following code inside Startup - ConfigureServices:

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie(options =>
                {

                    options.LoginPath = new PathString("/en/Authentication/LogIn");
                });

Everything works great, but I cannot find a way to make LoginPath being localisable using URL parameter (en/de/es etc.)

My MapControllerRoute looks like:

"{lang}/{controller=Home}/{action=Index}/{id?}"

Is it possible to redirect to appropriate lang for authentication like if user was accessing /de/NeedAuth/Index - it should be redirected to /de/Authentication/LogIn ?


Solution

  • Ok. I spent an hour and here is a solution - in case anyone would have similar use case.

    Step 1: Creating a new class that would dynamically get current http requests to determine redirection:

    public class CustomCookieAuthenticationEvents : CookieAuthenticationEvents
        {
            public override Task RedirectToLogin(RedirectContext<CookieAuthenticationOptions> context)
            {
                var httpContext = context.HttpContext;
    
                var routePrefix = httpContext.GetRouteValue("lang");
    
                context.RedirectUri = $"/{routePrefix.ToString()}/Authentication/LogIn";
                return base.RedirectToLogin(context);
            }
        }
    

    Step 2: In Startup modifying cookie authentication declaration that relates to redirecting to authentication page:

    services.AddScoped<CustomCookieAuthenticationEvents>();
                services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                    .AddCookie(options =>
                    {
                        options.LoginPath = new PathString("/Authentication/LogIn");
                        options.EventsType = typeof(CustomCookieAuthenticationEvents);
                    });
    

    Pay attention to registering CustomCookieAuthenticationEvents as service above.