Liferay 6.1 : get authentified Liferay user in a standalone context

Sometimes you need to develop outside the Liferay context, for example you have to create a custom servlet.

In some cases the authentified Liferay user & ThemeDisplay objects are not available. Here is a way to get the user from the cookies set by Liferay after successful login.

You should not use the below snippets as is to retrieve the authenticated user, this is not a safe way to be sure that the user that comes from the cookies is the one who is behind his screen. Someone might know how this cookie “ID” is generated and could easily generate a value that would impersonate another user. Be careful.

The cookie we are going to use is called “ID”, it is set when user successfully logs in (see LoginAction#login and LoginUtil#login)

1 – Get the cookie “ID”

Cookie[] cookies = request.getCookies();
String cookieIdValue = null;
if (cookies != null) {
   for (Cookie c : cookies) {
      if (CookieKeys.ID.equalsIgnoreCase(c.getName())) {
         cookieIdValue = c.getValue();
      }
   }
}

2 – Convert the hexadecimal cookie value to a String

String cookieUserId = new String(Hex.decodeHex(cookieIdValue.toCharArray()));

3 – Decrypt the user ID and fetch the user from DB

long companyId = PortalUtil.getCompanyId(request);
Company company = CompanyLocalServiceUtil.getCompanyById(companyId);
long userId = GetterUtil.getLong(Encryptor.decrypt(company.getKeyObj(), cookieUserId)     
return UserLocalServiceUtil.getUser(userId);

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s