Commit 5edf988a authored by Fabio Roberto Vitello's avatar Fabio Roberto Vitello
Browse files

initial release

parent 24b0b77b
Loading
Loading
Loading
Loading
+164 −0
Original line number Original line Diff line number Diff line
Shibboleth Authentication Plugin for Liferay
============================================

* This plugin is derived from an initial version of rsheshi@gmail.com. See: http://code.google.com/p/liferay-shibboleth-plugin/
* The first major extension was done by Ivan Novakov. https://github.com/ivan-novakov
* Further upgrades were made by Mihály Héder. https://github.com/mheder
* The latest extensions were made by Szabolcs Tenczer https://github.com/burgosz

Additional features has been added:

* auto create users using Shibboleth attributes (email, first name, last name)
* auto update user information upon login
* added options to specify the headers (Shibboleth attributes) to be used for extracting email, first name and last name
* basic attribute to role mapping

Requirements
------------

* Apache 2.x with mod_ssl and mod_proxy_ajp
* Shibboleth SP 2.x

Introduction
------------

Currently, there is no native Java Shibboleth service provider. If you need to protect your Java web
with Shibboleth, you have to run Apache with mod_shib in front of your servlet container (Tomcat, JBoss, ...).
The protected application must not be accessible directly, it must be run on a private address. Apache will intercept
requests, and after performing all authentication related tasks, it will pass the request to the backend servlet
container using AJP (Apache JServ Protocol).

Shibboleth Service Provider
---------------------------

A standard Shibboleth Service Provider instance may be used with one difference - the attribute preffix must bes
set to "AJP_", otherwise user attributes from Shibboleh will not be accessible in the application.

    <ApplicationDefaults entityID="https://liferay-test/shibboleth"
        REMOTE_USER="uid eppn persistent-id targeted-id" 
        attributePrefix="AJP_">


Apache configuration
--------------------

First, we need to set the AJP communication with the backend in our virtual host configuration:

    ProxyPass / ajp://localhost:8009/
    ProxyPassReverse / ajp://localhost:8009/
    
Then we'll configure Shibboleth to be "activated" for the whole site:

    <Location />
        AuthType shibboleth
        require shibboleth
    </Location>
    
And require a Shibboleth session at the "login" location:

    <Location /c/portal/login>
        AuthType shibboleth
        ShibRequireSession On
        require valid-user
    </Location>


Container's AJP connector
---------------------

Make sure, the backend servlet container has properly configured AJP connector. For example, in JBoss it is not enabled by default and you have to explicitly enable it:

    # cd $JBOSS_HOME/bin
    # ./jboss-cli.sh 
    You are disconnected at the moment. Type 'connect' to connect to the server or 'help' for the list of supported commands.
    [disconnected /] connect
    [standalone@localhost:9999 /] /subsystem=web:read-children-names(child-type=connector)
    {
        "outcome" => "success",
        "result" => ["http"]
    }
    [standalone@localhost:9999 /] /subsystem=web/connector=ajp:add(socket-binding=ajp, protocol="AJP/1.3", enabled=true, scheme=ajp)
    {"outcome" => "success"}
    [standalone@localhost:9999 /] /subsystem=web:read-children-names(child-type=connector)
    {
        "outcome" => "success",
        "result" => [
            "ajp",
            "http" 
        ]
    }


Plugin installation and configuration
-------------------------------------

Clone the repository and run the Maven install script:

    # git clone https://github.com/mheder/liferay-shibboleth-plugin
    # cd liferay-shibboleth-plugin
    # mvn install

Then deploy the WAR file to your servlet container.
After a successful installation a new "Shibboleth" section appears in the Liferay's Control panel at "Portal Settings / Authentication". You can adjust Shibboleth authentication there. The most important setting is the name of the attribute from with the user identity is taken.
At the same time, in "Portal Settings --> Authentication --> General", disable all "Allow..." options.

Further steps
-------------

If you plan to use Shibboleth autehtnication only, it will be a good idea to prevent your users from changing their personal info (especially the screen name which holds the identity). 

If you choose to auto-create users, you need to disable the "terms of use" page and the "security question", which appear to the new users. Add these directives to your portal-ext.properties:

    #
    # Set this to true to enable reminder queries that are used to help reset a
    # user's password.
    #
    users.reminder.queries.enabled=false
    users.reminder.queries.custom.question.enabled=false
    
    #
    # Set this to true if all users are required to agree to the terms of use.
    #
    terms.of.use.required=false

Logging can be enabled at "Control panel --> Server Administration --> Log Levels" by adding these categories:

    com.liferay.portal.security.auth.ShibbolethAutoLogin
    com.liferay.portal.servlet.filters.sso.shibboleth.ShibbolethFilter
    
These settings will work untill server reboot only. To make them permanent you need to create a special configuration file placed at `$JBOSS_HOME/standalone/deployments/ROOT.war/WEB-INF/classes/META-INF/portal-log4j-ext.xml`:

    <?xml version="1.0"?>
    <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
    
    <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
    
        <appender name="CONSOLE" class="org.apache.log4j.ConsoleAppender">
            <layout class="org.apache.log4j.PatternLayout">
                <param name="ConversionPattern" value="%d{ABSOLUTE} %-5p [%c{1}:%L] %m%n" />
            </layout>
        </appender>
    
        <category name="com.liferay.portal.security.auth.ShibbolethAutoLogin">
            <priority value="INFO" />
        </category>
    
        <category name="com.liferay.portal.servlet.filters.sso.shibboleth.ShibbolethFilter">
            <priority value="INFO" />
        </category>
    
    </log4j:configuration>



Licence
-------

[MIT Licence](http://opensource.org/licenses/mit-license.php)


Contact
-------

* homepage: https://github.com/ivan-novakov/liferay-shibboleth-plugin

pom.xml

0 → 100644
+95 −0
Original line number Original line Diff line number Diff line
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.github.ivan-novakov.liferay-shibboleth-plugin</groupId>
    <artifactId>liferay-shibboleth-plugin</artifactId>
    <packaging>war</packaging>
    <name>liferay-shibboleth-plugin</name>
    <url>https://github.com/ivan-novakov/liferay-shibboleth-plugin</url>
    <version>1.2</version>
    <properties>
        <liferay.auto.deploy.dir>/opt/lr/deploy</liferay.auto.deploy.dir>
        <liferay.version>6.2.0-RC5</liferay.version>
    </properties>
    <build>
        <finalName>shibboleth-plugin-hook</finalName>
        <plugins>
            <plugin>
                <groupId>com.liferay.maven.plugins</groupId>
                <artifactId>liferay-maven-plugin</artifactId>
                <version>${liferay.version}</version>
                <configuration>
                    <autoDeployDir>${liferay.auto.deploy.dir}</autoDeployDir>
                    <liferayVersion>${liferay.version}</liferayVersion>
                    <pluginType>hook</pluginType>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <encoding>UTF-8</encoding>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-resources-plugin</artifactId>
                <configuration>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.4</version>
                <configuration>
                    <webResources>
                        <resource>
                            <filtering>true</filtering>
                            <directory>src/main/webapp</directory>
                            <includes>
                                <include>**/liferay-plugin-package.xml</include>
                                <include>**/web.xml</include>
                            </includes>
                        </resource>
                    </webResources>
                    <warSourceDirectory>src/main/webapp</warSourceDirectory>
                    <webXml>src/main/webapp/WEB-INF/web.xml</webXml>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <dependency>
            <groupId>com.liferay.portal</groupId>
            <artifactId>portal-service</artifactId>
            <version>${liferay.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.liferay.portal</groupId>
            <artifactId>util-java</artifactId>
            <version>${liferay.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.portlet</groupId>
            <artifactId>portlet-api</artifactId>
            <version>2.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.4</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.0</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
</project>
+340 −0
Original line number Original line Diff line number Diff line
package com.liferay.portal.security.auth;

import com.liferay.portal.NoSuchUserException;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.model.CompanyConstants;
import com.liferay.portal.model.Role;
import com.liferay.portal.model.User;
import com.liferay.portal.security.ldap.PortalLDAPImporterUtil;
import com.liferay.portal.service.RoleLocalServiceUtil;
import com.liferay.portal.service.ServiceContext;
import com.liferay.portal.service.UserLocalServiceUtil;
import com.liferay.portal.shibboleth.util.ShibbolethPropsKeys;
import com.liferay.portal.shibboleth.util.Util;
import com.liferay.portal.util.PortalUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * Performs autologin based on the header values passed by Shibboleth.
 * 
 * The Shibboleth user ID header set in the configuration must contain the user
 * ID, if users are authenticated by screen name or the user email, if the users
 * are authenticated by email (Portal settings --> Authentication --> General).
 * 
 * @author Romeo Sheshi
 * @author Ivan Novakov <ivan.novakov@debug.cz>
 */
public class ShibbolethAutoLogin implements AutoLogin {

	private static Log _log = LogFactoryUtil.getLog(ShibbolethAutoLogin.class);

    @Override
    public String[] handleException(HttpServletRequest request, HttpServletResponse response, Exception e) throws AutoLoginException {
        // taken from BaseAutoLogin
        if (Validator.isNull(request.getAttribute(AutoLogin.AUTO_LOGIN_REDIRECT))) {
            throw new AutoLoginException(e);
        }
        _log.error(e, e);
        return null;
    }

    @Override
    public String[] login(HttpServletRequest req, HttpServletResponse res) throws AutoLoginException {

        User user;
        String[] credentials = null;
        HttpSession session = req.getSession(false);
        long companyId = PortalUtil.getCompanyId(req);


        try {
            _log.info("Shibboleth Autologin [modified 2]");

            if (!Util.isEnabled(companyId)) {
                return credentials;
            }

            user = loginFromSession(companyId, session);
            if (Validator.isNull(user)) {
                return credentials;
            }

            credentials = new String[3];
            credentials[0] = String.valueOf(user.getUserId());
            credentials[1] = user.getPassword();
            credentials[2] = Boolean.TRUE.toString();
            return credentials;

        } catch (NoSuchUserException e) {
            logError(e);
        } catch (Exception e) {
            logError(e);
            throw new AutoLoginException(e);
        }

        return credentials;
    }

    private User loginFromSession(long companyId, HttpSession session) throws Exception {
        String login;
        User user = null;

        login = (String) session.getAttribute(ShibbolethPropsKeys.SHIBBOLETH_LOGIN);
        if (Validator.isNull(login)) {
            return null;
        }

        String authType = Util.getAuthType(companyId);

        try {
            if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
                _log.info("Trying to find user with screen name: " + login);
                user = UserLocalServiceUtil.getUserByScreenName(companyId, login);
            } else if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {

                String emailAddress = (String) session.getAttribute(ShibbolethPropsKeys.SHIBBOLETH_HEADER_EMAIL);
                if (Validator.isNull(emailAddress)) {
                    return null;
                }

                _log.info("Trying to find user with email: " + emailAddress);
                user = UserLocalServiceUtil.getUserByEmailAddress(companyId, emailAddress);
            } else {
                throw new NoSuchUserException();
            }

            _log.info("User found: " + user.getScreenName() + " (" + user.getEmailAddress() + ")");

            if (Util.autoUpdateUser(companyId)) {
                _log.info("Auto-updating user...");
                updateUserFromSession(user, session);
            }

        } catch (NoSuchUserException e) {
            _log.error("User "  + login + " not found");

            if (Util.autoCreateUser(companyId)) {
                _log.info("Importing user from session...");
                user = createUserFromSession(companyId, session);
                _log.info("Created user with ID: " + user.getUserId());
            } else if (Util.importUser(companyId)) {
                _log.info("Importing user from LDAP...");
                user = PortalLDAPImporterUtil.importLDAPUser(companyId, StringPool.BLANK, login);
            }
        }

        try {
            updateUserRolesFromSession(companyId, user, session);
        } catch (Exception e) {
            _log.error("Exception while updating user roles from session: " + e.getMessage());
        }

        return user;
    }

    /**
     * Create user from session
     */
    protected User createUserFromSession(long companyId, HttpSession session) throws Exception {
        User user = null;

        String screenName = (String) session.getAttribute(ShibbolethPropsKeys.SHIBBOLETH_LOGIN);
        if (Validator.isNull(screenName)) {
            _log.error("Cannot create user - missing screen name");
            return user;
        }

        String emailAddress = (String) session.getAttribute(ShibbolethPropsKeys.SHIBBOLETH_HEADER_EMAIL);
        if (Validator.isNull(emailAddress)) {
            _log.error("Cannot create user - missing email");
            return user;
        }

        String firstname = (String) session.getAttribute(ShibbolethPropsKeys.SHIBBOLETH_HEADER_FIRSTNAME);
        if (Validator.isNull(firstname)) {
            _log.error("Cannot create user - missing firstname");
            return user;
        }

        String surname = (String) session.getAttribute(ShibbolethPropsKeys.SHIBBOLETH_HEADER_SURNAME);
        if (Validator.isNull(surname)) {
            _log.error("Cannot create user - missing surname");
            return user;
        }

        _log.info("Creating user: screen name = [" + screenName + "], emailAddress = [" + emailAddress
                + "], first name = [" + firstname + "], surname = [" + surname + "]");

        return addUser(companyId, screenName, emailAddress, firstname, surname);
    }

    /**
     * Store user
     */
    private User addUser(long companyId, String screenName, String emailAddress, String firstName, String lastName)
            throws Exception {

        long creatorUserId = 0;
        boolean autoPassword = true;
        String password1 = null;
        String password2 = null;
        boolean autoScreenName = false;
        long facebookId = 0;
        String openId = StringPool.BLANK;
        Locale locale = Locale.US;
        String middleName = StringPool.BLANK;
        int prefixId = 0;
        int suffixId = 0;
        boolean male = true;
        int birthdayMonth = Calendar.JANUARY;
        int birthdayDay = 1;
        int birthdayYear = 1970;
        String jobTitle = StringPool.BLANK;

        long[] groupIds = null;
        long[] organizationIds = null;
        long[] roleIds = null;
        long[] userGroupIds = null;

        boolean sendEmail = false;
        ServiceContext serviceContext = null;

        return UserLocalServiceUtil.addUser(creatorUserId, companyId, autoPassword, password1, password2,
                autoScreenName, screenName, emailAddress, facebookId, openId, locale, firstName, middleName, lastName,
                prefixId, suffixId, male, birthdayMonth, birthdayDay, birthdayYear, jobTitle, groupIds,
                organizationIds, roleIds, userGroupIds, sendEmail, serviceContext);
    }

    protected void updateUserFromSession(User user, HttpSession session) throws Exception {
        boolean modified = false;

        String emailAddress = (String) session.getAttribute(ShibbolethPropsKeys.SHIBBOLETH_HEADER_EMAIL);
        if (Validator.isNotNull(emailAddress) && !user.getEmailAddress().equals(emailAddress)) {
            _log.info("User [" + user.getScreenName() + "]: update email address [" + user.getEmailAddress()
                    + "] --> [" + emailAddress + "]");
            user.setEmailAddress(emailAddress);
            modified = true;
        }

        String firstname = (String) session.getAttribute(ShibbolethPropsKeys.SHIBBOLETH_HEADER_FIRSTNAME);
        if (Validator.isNotNull(firstname) && !user.getFirstName().equals(firstname)) {
            _log.info("User [" + user.getScreenName() + "]: update first name [" + user.getFirstName() + "] --> ["
                    + firstname + "]");
            user.setFirstName(firstname);
            modified = true;
        }

        String surname = (String) session.getAttribute(ShibbolethPropsKeys.SHIBBOLETH_HEADER_SURNAME);
        if (Validator.isNotNull(surname) && !user.getLastName().equals(surname)) {
            _log.info("User [" + user.getScreenName() + "]: update last name [" + user.getLastName() + "] --> ["
                    + surname + "]");
            user.setLastName(surname);
            modified = true;
        }

        if (modified) {
            UserLocalServiceUtil.updateUser(user);
        }
    }

    private void updateUserRolesFromSession(long companyId, User user, HttpSession session) throws Exception {
        if (!Util.autoAssignUserRole(companyId)) {
            return;
        }

        List<Role> currentFelRoles = getRolesFromSession(companyId, session);
        long[] currentFelRoleIds = roleListToLongArray(currentFelRoles);

        List<Role> felRoles = getAllRolesWithConfiguredSubtype(companyId);
        long[] felRoleIds = roleListToLongArray(felRoles);

        RoleLocalServiceUtil.unsetUserRoles(user.getUserId(), felRoleIds);
        RoleLocalServiceUtil.addUserRoles(user.getUserId(), currentFelRoleIds);

        _log.info("User '" + user.getScreenName() + "' has been assigned " + currentFelRoleIds.length + " role(s): "
                + Arrays.toString(currentFelRoleIds));
    }

    private long[] roleListToLongArray(List<Role> roles) {
        long[] roleIds = new long[roles.size()];

        for (int i = 0; i < roles.size(); i++) {
            roleIds[i] = roles.get(i).getRoleId();
        }

        return roleIds;
    }

    private List<Role> getAllRolesWithConfiguredSubtype(long companyId) throws Exception {
        String roleSubtype = Util.autoAssignUserRoleSubtype(companyId);
        return RoleLocalServiceUtil.getSubtypeRoles(roleSubtype);
    }

    private List<Role> getRolesFromSession(long companyId, HttpSession session) throws SystemException {
        List<Role> currentFelRoles = new ArrayList<Role>();
        String affiliation = (String) session.getAttribute(ShibbolethPropsKeys.SHIBBOLETH_HEADER_AFFILIATION);

        if (Validator.isNull(affiliation)) {
            return currentFelRoles;
        }

        String[] affiliationList = affiliation.split(";");
        for (String roleName : affiliationList) {
            Role role;
            try {
                role = RoleLocalServiceUtil.getRole(companyId, roleName);
            } catch (PortalException e) {
                _log.info("Exception while getting role with name '" + roleName + "': " + e.getMessage());
                try{
                    if(Util.isCreateRoleEnabled(companyId)){
                        List<Role> roleList = RoleLocalServiceUtil.getRoles(companyId);
                        long [] roleIds = roleListToLongArray(roleList);
                        Arrays.sort(roleIds);
                        long newId = roleIds[roleIds.length-1];
                        newId = newId+1;
                        role = RoleLocalServiceUtil.createRole(newId);

                        long classNameId = 0;
                        try{
                        	classNameId = RoleLocalServiceUtil.getRole(roleIds[roleIds.length-1]).getClassNameId();
                        }catch (PortalException ex){
                        	_log.info("classname error");
                        }
                        role.setClassNameId(classNameId);
        				role.setCompanyId(companyId);
        				role.setClassPK(newId);
        				role.setDescription(null);
        				role.setTitleMap(null);
        				role.setName(roleName);
        				role.setType(1);
        				RoleLocalServiceUtil.addRole(role);
                    }else continue;
                }catch (Exception exc){
                    continue;
                }        
            }

            currentFelRoles.add(role);
        }

        return currentFelRoles;
    }

    private void logError(Exception e) {
        _log.error("Exception message = " + e.getMessage() + " cause = " + e.getCause());
        if (_log.isDebugEnabled()) {
            _log.error(e);
        }

    }

}
 No newline at end of file
+218 −0

File added.

Preview size limit exceeded, changes collapsed.

+48 −0

File added.

Preview size limit exceeded, changes collapsed.

Loading