How to enable Remember me functionality in SAP Hybris?

Requirement: While login, the user should have the option (remember mecheckbox). If the user has selected checkbox, he/she should not ask to login again till remember me cookie expired.
Hybris OOTB behaviour: In the B2B site, there no remembers me checkbox, by default internally it's always selected. Means, soft login will work for all users. But Hybris also has a concept,Hard Login which matches secure GUID stored in session and cookie for all secured URL having the @RequireHardLogInannotation.
Changes Required:
  1. Remove default remember me (soft login) behaviour
  2. Add remember me checkbox in the login page
  3. Change Hard login behaviour, to regenerate GUID if auto-login perform for the current request.


1. Remove default remember me (soft login) behaviour

Find filespring-security-config.xml located in your storefront extension. Look for beandefaultRememberMeServices definition, in which attributealwaysRemember has valuetrue, that needs to be changed to false.
<alias name="defaultRememberMeServices" alias="rememberMeServices"/>
<bean id="defaultRememberMeServices" class="com.mysite.storefront.security.AcceleratorRememberMeServices" >
    <property name="userDetailsService" ref="originalUidUserDetailsService" />
    <property name="key" value="mysitestorefront" />
    <property name="cookieName" value="mysitestorefrontRememberMe" />
    <property name="alwaysRemember" value="false" />
    <property name="userService" ref="userService"/>
    <property name="useSecureCookie" value="true"/>
    <property name="customerFacade" ref="customerFacade"/>
    <property name="checkoutCustomerStrategy" ref="checkoutCustomerStrategy"/>
    <property name="urlEncoderService" ref="urlEncoderService"/>
    <property name="storeSessionFacade" ref="storeSessionFacade"/>
    <property name="commonI18NService" ref="commonI18NService"/>
    <property name="secureTokenService" ref="secureTokenService"/>
</bean>

2. Add remember me checkbox in the login page

Find out your login page JSP/TAG file (say login.tag), add below-mentioned code to your login form so the user will get remember me checkbox. You can also use Hybris formElement:formCheckboxinstead of a plain input box
<label><input type="checkbox" name="remember-me" class="checkbox" id="_spring_security_remember_me"  /> Remember Login</label>

3. Change Hard login behaviour

Note: Here you can skip this step if you want to keep OOTB hard login, which forces the user to re-login(if GUID not matches) when he/she try to access any secure URL.

Open fileRequireHardLoginBeforeControllerHandler.java and change methodbeforeController as mentioned below. Here, we check if GUID is invalid and remember me cookie present in the request, then we regenerate GUID and will proceed request further.
public static final String SECURE_REMEMBER_ME_COOKIES = "mysitestorefrontRememberMe";

@Resource(name = "guidCookieStrategy")
private GUIDCookieStrategy guidCookieStrategy;

@Override
public boolean beforeController(final HttpServletRequest request, final HttpServletResponse response,
        final HandlerMethod handler) throws Exception
{
    boolean redirect = true;

    // We only care if the request is secure
    if (request.isSecure())
    {
        // Check if the handler has our annotation
        final RequireHardLogIn annotation = findAnnotation(handler, RequireHardLogIn.class);
        if (annotation != null)
        {
            final String guid = (String) request.getSession().getAttribute(SECURE_GUID_SESSION_KEY);

            if ((!getUserService().isAnonymousUser(getUserService().getCurrentUser()) || checkForAnonymousCheckout())
                    && checkForGUIDCookie(request, response, guid))
            {
                redirect = false;
            }

            if (redirect)
            {
                if (isRememberMeCookiePresent(request))
                {
                    // If you find your guid is missing, lets recreate it.
                    guidCookieStrategy.setCookie(request, response);
                    return true;
                }
                else
                {
                    LOG.warn((guid == null ? "missing secure token in session" : "no matching guid cookie") + ", redirecting");
                    getRedirectStrategy().sendRedirect(request, response, getRedirectUrl(request));
                    return false;
                }
            }

        }
    }
    return true;
}


protected boolean isRememberMeCookiePresent(HttpServletRequest request)
{
    Cookie[] cookies = request.getCookies();

    if ((cookies == null) || (cookies.length == 0))
    {
        return false;
    }

    for (Cookie cookie : cookies)
    {
        if (SECURE_REMEMBER_ME_COOKIES.equals(cookie.getName()))
        {
            return cookie.getValue() != null;
        }
    }
    return false;
}
Author Image

Ankitkumar Patel

Sr. SAP Hybris consultant, having 15+ years experience in SAP Commerce Cloud (Hybris), SAP Spartacus. Extensive experience in SAP Hybris development, third-party integrations, project architecture and design... Read more

Comments

  1. Hi, i followed all the steps still its not working.. please help me

    ReplyDelete
    Replies
    1. Sure, tell me what exactly are you trying to achieve? are you getting any error?

      Delete
    2. Getting error in login url redirecting to spring check

      Delete
    3. Also make sure you set all properties correctly while declaring your rememberMeServices bean. Here I have set mysitestorefront, mysitestorefrontRememberMe etc, which needs to be changed accordingly to your site.

      Delete
    4. @Nanda, @Suresh - If you just want remember me functionality. Simply skip step 3 as I mentioned in the post.

      Once I get the time, I will re validate this post.

      Delete
  2. @All - Finally, today I have tried this with Hybris 6.7 unsuccessfully!!. What I found is, this was working with Hybris 5.X when I have created the post. In which I have used name="_spring_security_remember_me" while declaring checkbox. But new Hybris release have updated Spring Security. So you must use name="remember-me" of your check box. I already have updated the post.

    ReplyDelete
    Replies
    1. I am finding it difficult using the hybris checkbox tag:



      The formcheckbox uses "<form:checkbox" but it does not have a name attribute. It gets the value for the name attribute from the path value and the path is used for binding. The problem is that Java does not accept hyphen (-) as part of a method name so I am somewhat stuck.

      Do you have an idea which alternative that I can use apart from using a checkbox directly?

      Delete
  3. every b2b sites should require authentication/loginin before being able to access any page in website page like pdp page.how todo this task

    ReplyDelete
    Replies
    1. All you need to do is install secureportaladdon for your storefront.

      Delete
  4. Hi,
    Can you please help me out.

    My requirement is Persistence login user for 2 weeks

    1) if user check the checkbox then, he/she will be login for 2 weeks
    2) If the customer does not click the "Remember Me" checkbox, it does continue to be 20-30 minutes like it is now
    3)where we define the time for user login ?
    4) I have 1808 version , and have both b2b and b2c site in my code base ? Can you suggest for same code base how these functionality work ?

    ReplyDelete
  5. Sometimes my b2b site requires hard login, sometimes to go to Home Page and sometimes if I'm in product catalog, I want to deactivate it. Could you please help me?

    ReplyDelete

Post a Comment

Popular posts from this blog

Hybris flexible search query examples

How to Install temporary Hybris license?

How to remove or update all data records in Hybris?