Sitecore check user session and validate user if login onto different tabs or windows on same browser

Abhishek Malaviya
2 min readMay 10, 2019

--

We will implement httpRequestBegin pipeline to validate session and do request specific authentication logic.

Below code we are doing following activities:

  1. Validate user session — We are using CheckSession(bool isHomePage) method for this purpose. It’ll check, is user authenticated? If authentication fail then redirect to configure page ex- login or timeout page.
  2. If already login then can’t login with different login in same browser tabs or windows. Like how it happens in any standard site ex- gmail etc. Here we are using RedirectToLandingPage(bool isHomePage) method.

If user’s authentication is pass and user trying to open site URL in browser(chrome) different windows/tabs then user will be redirected to welcome/landing page.

namespace Sitecore.Foundation.Forms.Pipelines
{
public class ValidateUserSession: HttpRequestProcessor
{
public override void Process(HttpRequestArgs args)
{
var request = HttpContext.Current.Request;
//If Sitecore CMS URL then skip check
if (SitecoreContext.IsCMSRequest())
{
return;
}
//Here Home Page is login page.
var homePage = Context.Database.GetItem(Context.Site.StartPath);
var isHomePage = homePage.ID.Equals(Context.Item.ID);
if (Context.Item != null)
{
if (CheckSession(isHomePage))
{
RedirectToLandingPage(isHomePage);
}
}
}#region Private Methods
/// <summary>
/// Check user session, if not valid redirect to configure page.
/// </summary>
private bool CheckSession(bool isHomePage)
{
bool returnValue = true;
if (!isHomePage && !Context.User.IsAuthenticated)
{
string redirectUrl = FormsAuthentication.GetRedirectUrl(Context.User.Profile.UserName, true);
WebUtil.Redirect(redirectUrl);
returnValue=false;
}
return returnValue;
}
/// <summary>
/// If logged-in user trying to open url in browser different window/tab, user will redirect to landing/welcome page
/// </summary>
private void RedirectToLandingPage(bool isHomePage)
{
if(isHomePage)
{
var rootItem = Context.Database.GetItem(Context.Site.RootPath);
InternalLinkField link = rootItem[Constant.LandingPage];
string redirectUrl = Common.GenerateRedirecturl(redirectUrl, link);
HttpContext.Current.Response.Redirect(redirectUrl, false);
}
}

#endregion Private Methods
}
}

Add config patch file.

<sitecore>
<pipelines>
<httpRequestBegin>
<processor type=”Sitecore.Foundation.Forms.Pipelines.ValidateUserSession, Sitecore.Foundation.Forms” patch:after=”*[@type=’Sitecore.Pipelines.HttpRequest.ItemResolver, Sitecore.Kernel’]”/>
</httpRequestBegin>
</pipelines>
<settings>

--

--

No responses yet