oauthliferaysingle-sign-onautologinliferay-6.2

oAuth SSO on Liferay 6.2


I need to integrate on Liferay 6.2 GA6 a SSO from a web application that provide info by oAuth

A native support doesn't exist.

My problem is to create the automatic login on Liferay (after the user creation or if the user already exists). Any help ?


Solution

  • override portal.properties adding

    auto.login.hooks=com.yourpackage.hook.MyAutoLogin
    

    Create the class:

    package com.yourpackage.hook;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    
    import com.liferay.portal.kernel.exception.PortalException;
    import com.liferay.portal.kernel.exception.SystemException;
    import com.liferay.portal.kernel.util.ParamUtil;
    import com.liferay.portal.kernel.util.Validator;
    import com.liferay.portal.model.User;
    import com.liferay.portal.security.auth.AutoLogin;
    import com.liferay.portal.security.auth.AutoLoginException;
    import com.liferay.portal.service.UserLocalServiceUtil;
    import com.liferay.portal.util.PortalUtil;
    
    //based on example
    // https://bitbucket.org/brandizzi/liferay-examples/src/a41d71eba8f2fb2d4272a3ce8f393e77cec41d60/unsafe-login-hook/docroot/WEB-INF/src/br/brandizzi/adam/liferay/unsecure/UnsecureAutoLogin.java?at=default&fileviewer=file-view-default
    
    public class MyAutoLogin implements AutoLogin {
    
        @Override
        public String[] login(HttpServletRequest request,HttpServletResponse response) throws AutoLoginException {
    
            HttpSession session = request.getSession();
            String emailAddress = (String) session.getAttribute("LIFERAY_SHARED_EMAIL");
    
            if (emailAddress == null || emailAddress.isEmpty())
                return null;
    
    
                long companyId = PortalUtil.getCompanyId(request);
                User user = null;
                try {
                    user = UserLocalServiceUtil.getUserByEmailAddress(companyId, emailAddress);
                } catch (PortalException | SystemException e) {
    
                    e.printStackTrace();
                }
    
    
                String redirect = ParamUtil.getString(request, "redirect");
    
                if (Validator.isNotNull(redirect)) {
                    request.setAttribute(AutoLogin.AUTO_LOGIN_REDIRECT_AND_CONTINUE,PortalUtil.escapeRedirect(redirect));
                }
    
    
                String[] credentials = new String[3];
    
                                    credentials[0] = String.valueOf(user.getUserId());
                                    credentials[1] = user.getPassword();
                                    credentials[2] = String.valueOf(user.isPasswordEncrypted());
                                  //  credentials[2] =  Boolean.FALSE.toString();
            return credentials;
        }
    
        @Override
        public String[] handleException(HttpServletRequest arg0,
                HttpServletResponse arg1, Exception arg2)
                throws AutoLoginException {
    
            System.out.println("AutoLogin handleException ");
    
            return null;
        }
    }
    

    create an other class with the static methods:

    public static JSONObject doSSO(String firstname, String surname,  String email,  String username,String accessToken, ActionRequest actionRequest,   ActionResponse actionResponse){
    
        JSONObject jsonResp = JSONFactoryUtil.createJSONObject();
    
        //Get default Liferay company
         String webId = new String("liferay.com");
         Company company = null;
        try {
            company = CompanyLocalServiceUtil.getCompanyByWebId(webId);
        } catch (PortalException | SystemException e) {
          e.printStackTrace();
        }
    
    
        System.out.println("email "+email);
    
        User currentUser = null;
        try {
             currentUser = UserLocalServiceUtil.getUserByEmailAddress(company.getCompanyId(), email);
    
        } catch (SystemException | PortalException e) {
    
            System.out.println("User to create");
    
        }
    
        if (Validator.isNull(currentUser)){
    
            long newUserId = 0;
    
            try {
                jsonResp = addNewUser( firstname,  surname,   email,   username );
            } catch (Exception e) {
                e.printStackTrace();
            }
    
            String newUserIdS = jsonResp.getString("newUserId");
            newUserId = Long.valueOf(newUserIdS);
    
            try {
                currentUser = UserLocalServiceUtil.fetchUser(newUserId);
            } catch (SystemException e) {
                e.printStackTrace();
            }
    
            notifyAuthorAboutInvited(email, currentUser);
    
    
        }
    
        setExistingUserOnSession( actionRequest,currentUser, accessToken);
    
        //Login the user
        HttpServletRequest request = PortalUtil.getOriginalServletRequest(PortalUtil.getHttpServletRequest(actionRequest));
        HttpServletResponse response = PortalUtil.getHttpServletResponse(actionResponse);
    
        MyAutoLogin myLogin = new MyAutoLogin();
        try {
             myLogin.login(request, response);
             jsonResp.put("message","OK - User logged on Liferay");
        } catch (AutoLoginException e1) {
            e1.printStackTrace();
        }
    
    
    
        //set Token on customfield
        //remember to set permission guest to view and update
         ServiceContext serviceContext = null;
        try {
            serviceContext = ServiceContextFactory.getInstance(User.class.getName(), actionRequest);
        } catch (PortalException | SystemException e) {
            e.printStackTrace();
        }
         Map<String,Serializable> expandoBridgeAttributes = new HashMap<String, Serializable>();
         expandoBridgeAttributes.put("token", accessToken);  
         serviceContext.setExpandoBridgeAttributes(expandoBridgeAttributes);
         currentUser.setExpandoBridgeAttributes(serviceContext);
        try {
            UserLocalServiceUtil.updateUser(currentUser);
        } catch (SystemException e) {
            e.printStackTrace();
        }
    
    
        String userToken =currentUser.getExpandoBridge().getAttribute("token").toString();
        //System.out.println("doSSO accessToken dopo "+userToken);
    
    
        return jsonResp;
    }
    

    and:

    private static void setExistingUserOnSession(ActionRequest actionRequest,User user, String accessToken) {
    
        HttpServletRequest req = PortalUtil.getHttpServletRequest(actionRequest);
        HttpSession session = req.getSession();
        session.setAttribute("LIFERAY_SHARED_EMAIL", user.getEmailAddress());
    }