Redirect with query string parameters after authentication


A standard site behavior is to redirect users to the login page if they are trying to access a protected page. On successful authentication the user is redirected back to the page they had originally requested. This works well as long as the original request did not include a query string, as the query string is lost during re-directions. This might work if the query string does not govern the content of the page. But if it does the resulting page might not load the desired content. Luckily this issue can be resolved with just a few lines of code.
  1. We’ll create a new httpRequestBegin pipeline processor and add it to the pipeline
      
            
          
     
  2. Save the value of the query string to Sitecore Context Client data store (Sitecore.Context.ClientData)
    using Sitecore.Pipelines.HttpRequest;
    using Sitecore.Diagnostics;
    
    namespace XCore.SitecoreExtensions.Pipelines
    {
        public class SaveQueryString
        {
            public void Process(HttpRequestArgs args)
            {
                Assert.ArgumentNotNull(args, "args");
                // only save the querystring if the user is trying to access a page that requires login. after logging in read the client data to redirect user to the currect location
                if (args.PermissionDenied)
                    Sitecore.Context.ClientData.SetValue("qs", args.Context.Request.QueryString.ToString());
            }
        }
    }
     
  3. Append the stored query string to the redirection URL post authentication
    string savedQs = StringUtil.GetString(Sitecore.Context.ClientData.GetValue("qs"), "");
    			if (!string.IsNullOrEmpty(savedQs))
    			{
    				Sitecore.Context.ClientData.RemoveValue("qs");
    				return string.Format("{0}?{1}", StringUtil.GetString(redirectUrl, defaultUrl, "/"), savedQs);
    			}
       
Categories: Web Development
Tags: Sitecore;

SEARCH ARTICLES