Getting the Liferay User in a Standalone App

Jun 11, 2012   #java  #liferay  #security 

You can deploy a standard webapp in Liferay without making it a portlet.

If you do that, it is not so easy to get the currently logged in Liferay user in your standalone webapp. There is another article which suggests reconstructing the user with the information the Liferay login cookie provides. This solution has one blemish: It does only work when the user checks the “Remember me” box at the login screen. Otherwise the cookie won’t contain the password that is used in this approach for retrieving the user from Liferay.

I changed the solution mentioned above to only use the company key and the user id. This works even if the user did not check the “Remember me” box at the login screen. I made this a servlet filter which can be easily used by registering it in your web.xml.

Here’s what I came up with:

package com.codebrickie.filter;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.Key;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import com.liferay.portal.kernel.util.WebKeys;
import com.liferay.portal.model.Company;
import com.liferay.portal.model.User;
import com.liferay.portal.security.auth.PrincipalThreadLocal;
import com.liferay.portal.security.permission.PermissionChecker;
import com.liferay.portal.security.permission.PermissionCheckerFactoryUtil;
import com.liferay.portal.security.permission.PermissionThreadLocal;
import com.liferay.portal.service.CompanyLocalServiceUtil;
import com.liferay.portal.service.UserLocalServiceUtil;
import com.liferay.util.Encryptor;

public class LiferayUserFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain filterChain) throws IOException, ServletException {
        if (request instanceof HttpServletRequest) {
            Cookie[] cookies = ((HttpServletRequest) request).getCookies();
            String userId = null;
            String companyId = null;
            if (cookies != null) {
                for (Cookie c : cookies) {
                    if ("COMPANY_ID".equals(c.getName())) {
                        companyId = c.getValue();
                    } else if ("ID".equals(c.getName())) {
                        userId = hexStringToStringByAscii(c.getValue());
                    }
                }

                if (userId != null && companyId != null) {
                    try {
                        Company company = CompanyLocalServiceUtil.getCompany(Long
                                .parseLong(companyId));
                        Key key = company.getKeyObj();

                        String userIdPlain = Encryptor.decrypt(key, userId);

                        User liferayUser = UserLocalServiceUtil.getUser(Long.valueOf(userIdPlain));
                        
                        // Now you can set the liferayUser into a thread local for later use or 
                        // something like that.

                    } catch (Exception pException) {
                        throw new RuntimeException(pException);
                    }
                }
            }
        }
        filterChain.doFilter(request, response);
    }

    private String hexStringToStringByAscii(String hexString) {
        byte[] bytes = new byte[hexString.length() / 2];
        for (int i = 0; i < hexString.length() / 2; i++) {
            String oneHexa = hexString.substring(i * 2, i * 2 + 2);
            bytes[i] = Byte.parseByte(oneHexa, 16);
        }
        try {
            return new String(bytes, "ASCII");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }
    
    @Override
    public void destroy() {
        
    }
    
    @Override
    public void init(FilterConfig pArg0) throws ServletException {
        
    }
}