Search code examples
asp.neturl-routingform-authentication

Routing with ASP.NET Web Forms with Forms Authentication


FYI - This is not MVC.

I am using web form authentication and have the following in my web.config.

<authentication mode="Forms">
  <forms loginUrl="~/en/Admin/Login" timeout="2880" defaultUrl="/DashBoard" />
</authentication>

I am also using Routing for bilingual/culture.

My route looks like this:

RouteTable.Routes.MapPageRoute(
    routeName, "{lang}/Admin/Login", "/Admin/Login.aspx", true, defaults, constraints, dataTokens);

If a user tries to access a restricted page they will be redirected to /en/Admin/Login based the value in the web.config. My problem is if a user is viewing the site in french, the page is redirected to the English log in page when it needs to redirect to /fr/Admin/Login.

Is there any way around this as the entire site needs to be bilingual?


Solution

  • I found a similar issue with a few work arounds, but no true solution. How to redirect to a dynamic login URL in ASP.NET MVC

    Here's my solution:

    1) I added a session variable to keep track of what language the user has selected. (Ex: Session["lang"] = "fr")

    2) I made my login page /admin/default.aspx in the web.config like below:

    <authentication mode="Forms">
      <forms loginUrl="~/Admin/Default.aspx" timeout="2880" defaultUrl="/en/DashBoard" />
    </authentication>
    

    3) In my page load event for /admin/default.aspx I determine what language is set and redirect to the actual login page using the language from the session.

        if (HttpContext.Current.User.Identity.IsAuthenticated)
            // Redirect to dashboard
            ...
        else
        {
            string returnUrl = "";
            if (Request.QueryString["ReturnUrl"] != null)
                returnUrl = "?ReturnUrl=" + Request.QueryString["returnUrl"].ToString();
    
            string selectedLanguage = "";
            if (Session["lang"] != null)
                selectedLanguage = Session["lang"].ToString();
            else
                selectedLanguage = "en";
    
            string loginURL = ConfigurationManager.AppSettings["Auth.LoginUrl"].ToString();
            loginURL = loginURL.Replace("{lang}", selectedLanguage);
    
            Response.Redirect(loginURL + returnUrl);                
        }