Improving LifeRay 6 CAS integration

Lately, I had the dubious pleasure of integrating CAS with LifeRay (the results of which can be seen in my previous posts). Unfortunately, LifeRay assumes that both CAS and LifeRay are connected to the same user store (LDAP server or any similar security store), and thus no user import is necessary. But, as CAS has a much wider range of supported user stores – this is not always the case.
I needed to address this issue, meaning – allow users to login through CAS, even if they are not LifeRay users.


I replaced LifeRay CAS filter, and made sure that the AttributePrincipal object arriving from CAS client is stored at the HTTPSession.
Then, I replaced LifeRay auto-login class, and used LifeRay API to create a user if a user has logged in but did not exist in the internal LifeRay user database.

July-17, 2013 – Since I got many comments on this topic, I decided to open source the code mentioned here. Please see for details.

The How

Here’s what I did:

  1. Configure LifeRay for CAS (see my previous post –, but DON’T configure the LifeRay for LDAP
  2. Create a new Java project.
  3. As I use Maven, I used the following pom.xml file:
    <?xml version="1.0"?>
        xmlns="" xmlns:xsi="">
  4. I create a new class, called TonaCASFilter, that derives from CASFilter. Note that I had to copy some code from the parent class, as it was not easily extensible 😦
    public class TonaCasFilter extends CASFilter {
    	public static String LOGIN = CASFilter.class.getName() + "LOGIN";
    	public static void reload(long companyId) {
    	protected Log getLog() {
    		return _log;
    	protected TicketValidator getTicketValidator(long companyId)
    		throws Exception {
    		TicketValidator ticketValidator = _ticketValidators.get(companyId);
    		if (ticketValidator != null) {
    			return ticketValidator;
    		String serverName = PrefsPropsUtil.getString(
    			companyId, PropsKeys.CAS_SERVER_NAME, PropsValues.CAS_SERVER_NAME);
    		String serverUrl = PrefsPropsUtil.getString(
    			companyId, PropsKeys.CAS_SERVER_URL, PropsValues.CAS_SERVER_URL);
    		String loginUrl = PrefsPropsUtil.getString(
    			companyId, PropsKeys.CAS_LOGIN_URL, PropsValues.CAS_LOGIN_URL);
    		Saml11TicketValidator cas20ProxyTicketValidator = new Saml11TicketValidator(serverUrl);
    		Map parameters = new HashMap();
    		parameters.put("serverName", serverName);
    		parameters.put("casServerUrlPrefix", serverUrl);
    		parameters.put("casServerLoginUrl", loginUrl);
    		parameters.put("redirectAfterValidation", "false");
    		_ticketValidators.put(companyId, cas20ProxyTicketValidator);
    		return cas20ProxyTicketValidator;
    	protected void processFilter(
    			HttpServletRequest request, HttpServletResponse response,
    			FilterChain filterChain)
    		throws Exception {
    		long companyId = PortalUtil.getCompanyId(request);
    		if (PrefsPropsUtil.getBoolean(
    				companyId, PropsKeys.CAS_AUTH_ENABLED,
    				PropsValues.CAS_AUTH_ENABLED)) {
    			HttpSession session = request.getSession();
    			String pathInfo = request.getPathInfo();
    			if (pathInfo.indexOf("/portal/logout") != -1) {
    				String logoutUrl = PrefsPropsUtil.getString(
    					companyId, PropsKeys.CAS_LOGOUT_URL,
    			else {
    				String login = (String)session.getAttribute(LOGIN);
    				String serverName = PrefsPropsUtil.getString(
    					companyId, PropsKeys.CAS_SERVER_NAME,
    				String serviceUrl = PrefsPropsUtil.getString(
    					companyId, PropsKeys.CAS_SERVICE_URL,
    				if (Validator.isNull(serviceUrl)) {
    					serviceUrl = CommonUtils.constructServiceUrl(
    						request, response, serviceUrl, serverName, "ticket",
    				String ticket = ParamUtil.getString(request, "ticket");
    				if (Validator.isNull(ticket)) {
    					if (Validator.isNotNull(login)) {
    								TonaCasFilter.class, request, response, filterChain);
    					else {
    						String loginUrl = PrefsPropsUtil.getString(
    							companyId, PropsKeys.CAS_LOGIN_URL,
    						loginUrl = HttpUtil.addParameter(
    							loginUrl, "service", serviceUrl);
    				TicketValidator ticketValidator = getTicketValidator(
    				Assertion assertion = ticketValidator.validate(
    					ticket, serviceUrl);
    				if (assertion != null) {
    					AttributePrincipal attributePrincipal =
    					login = attributePrincipal.getName();
    					session.setAttribute(LOGIN, login);
    					session.setAttribute("principal", attributePrincipal);
    		processFilter(TonaCasFilter.class, request, response, filterChain);
    	private static Log _log = LogFactoryUtil.getLog(TonaCasFilter.class);
    	private static Map _ticketValidators =
    		new ConcurrentHashMap();
  5. I then create the new auto-login class. Again – as it was not very extendible, I had to copy-paste allot of code from the parent class…
    public class TonaCASAutoLogin extends CASAutoLogin {
    	private Logger logger = LoggerFactory.getLogger(TonaCASAutoLogin.class.getName());
    	public String[] login(HttpServletRequest request, HttpServletResponse response) {
    		String[] credentials = null;
    		try {
    			long companyId = PortalUtil.getCompanyId(request);
    			if (!PrefsPropsUtil.getBoolean(companyId, PropsKeys.CAS_AUTH_ENABLED, PropsValues.CAS_AUTH_ENABLED)) {
    				return credentials;
    			HttpSession session = request.getSession();
    			String login = (String) session.getAttribute(CASFilter.LOGIN);
    			if (Validator.isNull(login)) {
    				return credentials;
    			AttributePrincipal principal = (AttributePrincipal) session.getAttribute("principal");
    			if (principal != null) {
    				Map attrs = principal.getAttributes();
    				Object groupMembership = attrs.get(Configuration.getInstance().getMemberOfProperty());
    				if (groupMembership != null) {
    					com.liferay.portal.service.ServiceContext context = new com.liferay.portal.service.ServiceContext();
    					User user = null;
    					String email = attrs.get("email").toString();
    					String lastName = attrs.get("lastName").toString();
    					String firstName = attrs.get("firstName").toString();
    					try {
    						user = UserLocalServiceUtil.getUserByScreenName(companyId, login);
    					} catch (NoSuchUserException nsue) {
    						// User not found.
    					// The groups the user needs to belong to
    					long[] mapToGroupsArray = getUserGroups(companyId, groupMembership.toString());
    					// The community we want to map the user to
    					long groupId = 10131;
    					// User not found - create it.
    					if (user == null) {
    						try {
    							UserLocalServiceUtil.addUser(0, companyId, false, "not-used", "not-used", false,
    									fixScreenName(login), email, 0, "", Locale.getDefault(), firstName, "", lastName,
    									0, 0, true, 1, 1, 1970, null, new long[] {groupId}, null, null, mapToGroupsArray, false, context);
    						} catch (Exception e) {
    							logger.error("Can't add user", e);
    					} else {
    						// User exists - remap groups
    						UserGroupLocalServiceUtil.setUserUserGroups(user.getUserId(), mapToGroupsArray);
    						// Ensure user has the right community
    						UserLocalServiceUtil.addGroupUsers(groupId, new long[] { user.getUserId()});
    			return super.login(request, response);
    		} catch (Throwable e) {
    			logger.error("Can't auto-login, reverting to default behavior", e);
    		return super.login(request, response);
    	private String fixScreenName(String loginName) {
    		String name = loginName;
    		if (name.contains("@")) {
    			name = name.substring(0,name.indexOf("@"));
    		return name;
    	private long[] getUserGroups(long companyId, String groupMembership) throws Exception {
    		String[] groups = groupMembership.toString().split(";");
    		List mapToGroups = new ArrayList();
    		for (String group : groups) {
    			if (group.contains("[")) {
    				group = group.replace('[', ' ');
    				group = group.replace(']', ' ');
    				group = group.trim();
    			String groupName = group;
    			if (groupName != null) {
    				UserGroup liferayGroup = UserGroupLocalServiceUtil.getUserGroup(companyId, groupName);
    				if (liferayGroup != null) {
    					logger.debug("Found user group " + liferayGroup.getUserGroupId());
    				} else {
    					logger.debug("Liferay group " + groupName + " not found");
    		long[] mapToGroupsArray = new long[mapToGroups.size()];
    		int i = 0;
    		for (long l : mapToGroups) {
    			mapToGroupsArray[i] = l;
    		return mapToGroupsArray;
    Note that you must make sure CAS sends all the relevant properties in the return SAML response, and that the groups sent exist in LifeRay. 
    <li>Now, create a JAR file (<code>mvn clean install</code>), and copy the JAR file to <code>TOMCAT_HOME/webapps/ROOT/WEB-INF/lib</code></li>
    	<li>Edit the LifeRay web.xml file. It can be found in <code>TOMCAT_HOME/webapps/ROOT/WEB-INF</code>. Replace the line
    with the following line:
  6. Edit the LifeRay file. It can be found in TOMCAT_HOME/webapps/ROOT/WEB-INF/classes. Add the following line:
  7. Restart LifeRay. All should work...

Configuring LifeRay and CAS to work with LDAP

I saw many tutorials on CAS, Liferay and LDAP – but unfortunetly, none of them worked for me. So I decided to document what does work (at least for me).
Note that my environment is based on LifeRay 6.0.5 and CAS 3.5.1.

  1. Configure Tomcat for SSL. I have used port 443. You can read all about it here
    1. After creating the certificates, I just ended up with adding the following tag in TOMCAT_HOME/conf/server.xml
                 port="443" maxThreads="200"
                 scheme="https" secure="true" SSLEnabled="true"
                 keystoreFile="/root/.keystore" keystorePass="password"
                 clientAuth="false" sslProtocol="TLS"/>  
    3. IMPORTANT I did not manage to make CAS work with a self signed certificate, so I’ve used a temporary free one.
  2. Configure LifeRay for LDAP
    1. Login to LifeRay
    2. Go to the Control Panel–>Settings–>Authentication–>LDAP
    3. Ensure the “Enabled” check box is selected
    4. I strongly suggest enabling the “Import” checkbox and ensure Import is enabled for server startup.
    5. Add a server
    6. Fill in the LDAP server details (it’s easy to check them with an LDAP browser like jxplorer)
    7. Save your configuration
    8. I usually restart Tomcat after that change, and view the log to see all users were successfully imported
  3. Build CAS
    1. Download CAS (I downloaded it from here)
    2. Unzip the file
    3. Edit the CAS_HOME/cas-server-webapp/pom.xml file and add the following:
    4. <dependency>
    5. Build CAS using maven. The command to run is mvn clean install
  4. Deploy CAS
    1. Copy the newly created WAR file from CAS_HOME/cas-server-webapp/target/cas.war to TOMCAT_HOME/webapps
  5. Configure CAS for LDAP
    1. Edit the TOMCAT_HOME/webapps/cas/WEB-INF/deployerConfigContext.xml
    2. Add the following at the end of the file (just before the /beans tag)
    3. <bean id="contextSource" class="">
        <!-- DO NOT enable JNDI pooling for context sources that perform LDAP bind operations. -->
        <property name="pooled" value="false"/>
          Although multiple URLs may defined, it's strongly recommended to avoid this configuration
          since the implementation attempts hosts in sequence and requires a connection timeout
          prior to attempting the next host, which incurs unacceptable latency on node failure.
          A proper HA setup for LDAP directories should use a single virtual host that maps to multiple
          real hosts using a hardware load balancer.
        <property name="url" value="ldap://LDAP_SERVER:389" />
          Manager credentials are only required if your directory does not support anonymous searches.
          Never provide these credentials for FastBindLdapAuthenticationHandler since the user's
          credentials are used for the bind operation.
        <property name="userDn" value="cn=Manager"/>
        <property name="password" value="test"/>
        <!-- Place JNDI environment properties here. -->
        <property name="baseEnvironmentProperties">
            <!-- Three seconds is an eternity to users. -->
            <entry key="com.sun.jndi.ldap.connect.timeout" value="3000" />
            <entry key="" value="3000" />
            <!-- Explained at -->
            <entry key="" value="simple" />
    4. Add the following under the list tag of the authenticationHandlers tag
    5.       <bean class="org.jasig.cas.adaptors.ldap.BindLdapAuthenticationHandler"
      p:contextSource-ref="contextSource" />
  6. Configure LifeRay for CAS
    1. Login to LifeRay
    2. Go to the Control Panel–>Settings–>Authentication–>CAS
    3. Ensure the “Enabled” check box is selected
    4. Ensure the “LDAP Import” check box is selected
    5. Enter the URLs of the CAS server
    6. Save
    7. Add the following line to TOMCAT_HOME/webapps/ROOT/WEB-INF/classes/
    8. com.liferay.filters.sso.cas.CASFilter=true
    9. Add the following line to TOMCAT_HOME/webapps/ROOT/WEB-INF/classes/
    11. Restart Tomcat

You can now access your LifeRay instance, and get the CAS login instead…