Search in sources :

Example 1 with AuthenticationService

use of org.alfresco.service.cmr.security.AuthenticationService in project acs-community-packaging by Alfresco.

the class AlfrescoFacesPortlet method facesRender.

/**
 * @see org.apache.myfaces.portlet.MyFacesGenericPortlet#facesRender(javax.portlet.RenderRequest, javax.portlet.RenderResponse)
 */
protected void facesRender(RenderRequest request, RenderResponse response) throws PortletException, IOException {
    Application.setInPortalServer(true);
    try {
        // Set the current locale
        I18NUtil.setLocale(getLanguage(request.getPortletSession()));
        if (request.getParameter(ERROR_OCCURRED) != null) {
            String errorPage = getErrorPage();
            if (logger.isDebugEnabled())
                logger.debug("An error has occurred, redirecting to error page: " + errorPage);
            response.setContentType("text/html");
            PortletRequestDispatcher dispatcher = getPortletContext().getRequestDispatcher(errorPage);
            dispatcher.include(request, response);
        } else {
            WebApplicationContext ctx = (WebApplicationContext) getPortletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
            AuthenticationService auth = (AuthenticationService) ctx.getBean("AuthenticationService");
            // if we have no User object in the session then an HTTP Session timeout must have occured
            // use the viewId to check that we are not already on the login page
            PortletSession session = request.getPortletSession();
            String viewId = request.getParameter(VIEW_ID);
            // keep track of last view id so we can use it as return page from multi-part requests
            request.getPortletSession().setAttribute(SESSION_LAST_VIEW_ID, viewId);
            SessionUser sessionUser = (SessionUser) request.getPortletSession().getAttribute(AuthenticationHelper.AUTHENTICATION_USER, PortletSession.APPLICATION_SCOPE);
            User user = sessionUser instanceof User ? (User) sessionUser : null;
            if (user == null && (viewId == null || viewId.equals(getLoginPage()) == false)) {
                if (portalGuestAuthenticate(ctx, session, auth) != null) {
                    if (logger.isDebugEnabled())
                        logger.debug("Guest access successful.");
                    // perform the forward to the page processed by the Faces servlet
                    response.setContentType("text/html");
                    request.getPortletSession().setAttribute(PortletUtil.PORTLET_REQUEST_FLAG, "true");
                    // get the start location as configured by the web-client config
                    ConfigService configService = (ConfigService) ctx.getBean("webClientConfigService");
                    ClientConfigElement configElement = (ClientConfigElement) configService.getGlobalConfig().getConfigElement("client");
                    if (NavigationBean.LOCATION_MYALFRESCO.equals(configElement.getInitialLocation())) {
                        nonFacesRequest(request, response, "/jsp/dashboards/container.jsp");
                    } else {
                        nonFacesRequest(request, response, FacesHelper.BROWSE_VIEW_ID);
                    }
                } else {
                    if (logger.isDebugEnabled())
                        logger.debug("No valid User login, requesting login page. ViewId: " + viewId);
                    // set last used username as special session value used by the LoginBean
                    session.setAttribute(AuthenticationHelper.SESSION_USERNAME, request.getPreferences().getValue(PREF_ALF_USERNAME, null));
                    // login page is the default portal page
                    response.setContentType("text/html");
                    request.getPortletSession().setAttribute(PortletUtil.PORTLET_REQUEST_FLAG, "true");
                    nonFacesRequest(request, response);
                }
            } else {
                if (session.getAttribute(AuthenticationHelper.SESSION_INVALIDATED) != null) {
                    // remove the username preference value as explicit logout was requested by the user
                    if (request.getPreferences().isReadOnly(PREF_ALF_USERNAME) == false) {
                        request.getPreferences().reset(PREF_ALF_USERNAME);
                    }
                    session.removeAttribute(AuthenticationHelper.SESSION_INVALIDATED);
                }
                try {
                    if (user != null) {
                        if (logger.isDebugEnabled())
                            logger.debug("Validating ticket: " + user.getTicket());
                        // setup the authentication context
                        auth.validate(user.getTicket());
                    }
                    // do the normal JSF processing
                    super.facesRender(request, response);
                } catch (AuthenticationException authErr) {
                    // ticket is no longer valid!
                    if (logger.isDebugEnabled())
                        logger.debug("Invalid ticket, requesting login page.");
                    // remove User object as it's now useless
                    session.removeAttribute(AuthenticationHelper.AUTHENTICATION_USER, PortletSession.APPLICATION_SCOPE);
                    // login page is the default portal page
                    response.setContentType("text/html");
                    request.getPortletSession().setAttribute(PortletUtil.PORTLET_REQUEST_FLAG, "true");
                    nonFacesRequest(request, response);
                } catch (Throwable e) {
                    if (getErrorPage() != null) {
                        handleError(request, response, e);
                    } else {
                        logger.warn("No error page configured, re-throwing exception");
                        if (e instanceof PortletException) {
                            throw (PortletException) e;
                        } else if (e instanceof IOException) {
                            throw (IOException) e;
                        } else {
                            throw new PortletException(e);
                        }
                    }
                }
            }
        }
    } finally {
        Application.setInPortalServer(false);
    }
}
Also used : User(org.alfresco.web.bean.repository.User) SessionUser(org.alfresco.repo.SessionUser) AuthenticationException(org.alfresco.repo.security.authentication.AuthenticationException) PortletException(javax.portlet.PortletException) IOException(java.io.IOException) ClientConfigElement(org.alfresco.web.config.ClientConfigElement) WebApplicationContext(org.springframework.web.context.WebApplicationContext) PortletRequestDispatcher(javax.portlet.PortletRequestDispatcher) SessionUser(org.alfresco.repo.SessionUser) ConfigService(org.springframework.extensions.config.ConfigService) PortletSession(javax.portlet.PortletSession) AuthenticationService(org.alfresco.service.cmr.security.AuthenticationService)

Example 2 with AuthenticationService

use of org.alfresco.service.cmr.security.AuthenticationService in project acs-community-packaging by Alfresco.

the class AuthenticationHelper method getUser.

/**
 * Attempts to retrieve the User object stored in the current session.
 *
 * @param sc
 *            the servlet context
 * @param httpRequest
 *            The HTTP request
 * @param httpResponse
 *            The HTTP response
 * @return The User object representing the current user or null if it could not be found
 */
public static User getUser(final ServletContext sc, final HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
    // If the remote user mapper is configured, we may be able to map in an externally authenticated user
    String userId = getRemoteUser(sc, httpRequest);
    final WebApplicationContext wc = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
    HttpSession session = httpRequest.getSession();
    User user = null;
    // examine the appropriate session to try and find the User object
    SessionUser sessionUser = Application.getCurrentUser(session);
    // been known to leak in but shouldn't now)
    if (sessionUser != null) {
        if (logger.isDebugEnabled())
            logger.debug("SessionUser is: " + sessionUser.getUserName());
        AuthenticationService auth = (AuthenticationService) wc.getBean(AUTHENTICATION_SERVICE);
        try {
            auth.validate(sessionUser.getTicket());
            if (sessionUser instanceof User) {
                user = (User) sessionUser;
                setExternalAuth(session, userId != null);
            } else {
                user = setUser(sc, httpRequest, sessionUser.getUserName(), sessionUser.getTicket(), userId != null);
            }
        } catch (AuthenticationException authErr) {
            if (logger.isDebugEnabled())
                logger.debug("An authentication error occured while setting the session user", authErr);
            session.removeAttribute(AUTHENTICATION_USER);
            if (!Application.inPortalServer()) {
                if (logger.isDebugEnabled())
                    logger.debug("Invalidating the session.");
                session.invalidate();
            }
        }
    }
    // If the remote user mapper is configured, we may be able to map in an externally authenticated user
    if (userId != null) {
        AuthorityService authorityService = (AuthorityService) wc.getBean(AUTHORITY_SERVICE);
        // We have a previously-cached user with the wrong identity - replace them
        if (user != null && !authorityService.isGuestAuthority(user.getUserName()) && !user.getUserName().equals(userId)) {
            if (logger.isDebugEnabled())
                logger.debug("We have a previously-cached user with the wrong identity - replace them");
            session.removeAttribute(AUTHENTICATION_USER);
            if (!Application.inPortalServer()) {
                if (logger.isDebugEnabled())
                    logger.debug("Invalidating session.");
                session.invalidate();
            }
            user = null;
        }
        if (user == null) {
            if (logger.isDebugEnabled())
                logger.debug("There are no previously-cached users.");
            // If we have been authenticated by other means, just propagate through the user identity
            AuthenticationComponent authenticationComponent = (AuthenticationComponent) wc.getBean(AUTHENTICATION_COMPONENT);
            try {
                if (logger.isDebugEnabled())
                    logger.debug("We have been authenticated by other means, authenticating the user: " + userId);
                authenticationComponent.setCurrentUser(userId);
                AuthenticationService authenticationService = (AuthenticationService) wc.getBean(AUTHENTICATION_SERVICE);
                user = setUser(sc, httpRequest, userId, authenticationService.getCurrentTicket(), true);
            } catch (AuthenticationException authErr) {
                if (logger.isDebugEnabled())
                    logger.debug("An authentication error occured while setting the session user", authErr);
                // Allow for an invalid external user ID to be indicated
                session.removeAttribute(AUTHENTICATION_USER);
                if (!Application.inPortalServer()) {
                    if (logger.isDebugEnabled())
                        logger.debug("Invalidating the session.");
                    session.invalidate();
                }
            }
        }
    }
    return user;
}
Also used : SessionUser(org.alfresco.repo.SessionUser) SessionUser(org.alfresco.repo.SessionUser) User(org.alfresco.web.bean.repository.User) AuthenticationComponent(org.alfresco.repo.security.authentication.AuthenticationComponent) AuthenticationException(org.alfresco.repo.security.authentication.AuthenticationException) HttpSession(javax.servlet.http.HttpSession) AuthorityService(org.alfresco.service.cmr.security.AuthorityService) AuthenticationService(org.alfresco.service.cmr.security.AuthenticationService) WebApplicationContext(org.springframework.web.context.WebApplicationContext)

Example 3 with AuthenticationService

use of org.alfresco.service.cmr.security.AuthenticationService in project acs-community-packaging by Alfresco.

the class AuthenticationHelper method authenticate.

/**
 * Helper to authenticate the current user using the supplied Ticket value.
 *
 * @return true if authentication successful, false otherwise.
 */
public static AuthenticationStatus authenticate(ServletContext context, HttpServletRequest httpRequest, HttpServletResponse httpResponse, String ticket) throws IOException {
    if (logger.isDebugEnabled())
        logger.debug("Authenticate the current user using the supplied Ticket value.");
    // setup the authentication context
    WebApplicationContext wc = WebApplicationContextUtils.getRequiredWebApplicationContext(context);
    AuthenticationService auth = (AuthenticationService) wc.getBean(AUTHENTICATION_SERVICE);
    HttpSession session = httpRequest.getSession();
    try {
        // If we already have a cached user, make sure it is for the right ticket
        SessionUser user = (SessionUser) session.getAttribute(AuthenticationHelper.AUTHENTICATION_USER);
        if (user != null && !user.getTicket().equals(ticket)) {
            if (logger.isDebugEnabled())
                logger.debug("Found a previously-cached user with the wrong identity.");
            session.removeAttribute(AUTHENTICATION_USER);
            if (!Application.inPortalServer()) {
                if (logger.isDebugEnabled())
                    logger.debug("The server is not running in a portal, invalidating session.");
                session.invalidate();
                session = httpRequest.getSession();
            }
            user = null;
        }
        // Validate the ticket and associate it with the session
        auth.validate(ticket);
        if (user == null) {
            if (logger.isDebugEnabled())
                logger.debug("Ticket is valid; caching a new user in the session.");
            setUser(context, httpRequest, auth.getCurrentUserName(), ticket, false);
        } else if (logger.isDebugEnabled())
            logger.debug("Ticket is valid; retaining cached user in session.");
    } catch (AuthenticationException authErr) {
        if (logger.isDebugEnabled())
            logger.debug("An AuthenticationException occured: ", authErr);
        session.removeAttribute(AUTHENTICATION_USER);
        if (!Application.inPortalServer()) {
            if (logger.isDebugEnabled())
                logger.debug("The server is not running in a portal, invalidating session.");
            session.invalidate();
        }
        return AuthenticationStatus.Failure;
    } catch (Throwable e) {
        if (logger.isDebugEnabled())
            logger.debug("Authentication failed due to unexpected error", e);
        // Some other kind of serious failure
        AuthenticationService unprotAuthService = (AuthenticationService) wc.getBean(UNPROTECTED_AUTH_SERVICE);
        unprotAuthService.invalidateTicket(unprotAuthService.getCurrentTicket());
        unprotAuthService.clearCurrentSecurityContext();
        return AuthenticationStatus.Failure;
    }
    // As we are authenticating via a ticket, establish the session locale using request headers rather than web client preferences
    setupThread(context, httpRequest, httpResponse, false);
    return AuthenticationStatus.Success;
}
Also used : SessionUser(org.alfresco.repo.SessionUser) AuthenticationException(org.alfresco.repo.security.authentication.AuthenticationException) HttpSession(javax.servlet.http.HttpSession) AuthenticationService(org.alfresco.service.cmr.security.AuthenticationService) WebApplicationContext(org.springframework.web.context.WebApplicationContext)

Example 4 with AuthenticationService

use of org.alfresco.service.cmr.security.AuthenticationService in project acs-community-packaging by Alfresco.

the class GuestTemplateContentServlet method buildModel.

@Override
protected Map<String, Object> buildModel(ServiceRegistry services, HttpServletRequest req, NodeRef templateRef) {
    // setup the guest user to pass to the build model helper method
    AuthenticationService auth = (AuthenticationService) services.getAuthenticationService();
    PersonService personService = (PersonService) services.getPersonService();
    NodeService nodeService = (NodeService) services.getNodeService();
    NodeRef guestRef = personService.getPerson(AuthenticationUtil.getGuestUserName());
    User guestUser = new User(AuthenticationUtil.getGuestUserName(), auth.getCurrentTicket(), guestRef);
    NodeRef guestHomeRef = (NodeRef) nodeService.getProperty(guestRef, ContentModel.PROP_HOMEFOLDER);
    if (nodeService.exists(guestHomeRef) == false) {
        throw new InvalidNodeRefException(guestHomeRef);
    }
    guestUser.setHomeSpaceId(guestHomeRef.getId());
    // build the default model
    return DefaultModelHelper.buildDefaultModel(services, guestUser, templateRef, this.imageResolver);
}
Also used : NodeRef(org.alfresco.service.cmr.repository.NodeRef) User(org.alfresco.web.bean.repository.User) PersonService(org.alfresco.service.cmr.security.PersonService) NodeService(org.alfresco.service.cmr.repository.NodeService) InvalidNodeRefException(org.alfresco.service.cmr.repository.InvalidNodeRefException) AuthenticationService(org.alfresco.service.cmr.security.AuthenticationService)

Example 5 with AuthenticationService

use of org.alfresco.service.cmr.security.AuthenticationService in project acs-community-packaging by Alfresco.

the class AuthenticationHelper method authenticate.

/**
 * Helper to authenticate the current user using session based Ticket information.
 * <p>
 * User information is looked up in the Session. If found the ticket is retrieved and validated.
 * If no User info is found or the ticket is invalid then a redirect is performed to the login page.
 *
 * @param forceGuest       True to force a Guest login attempt
 * @param allowGuest       True to allow the Guest user if no user object represent
 *
 * @return AuthenticationStatus result.
 */
public static AuthenticationStatus authenticate(ServletContext sc, HttpServletRequest req, HttpServletResponse res, boolean forceGuest, boolean allowGuest) throws IOException {
    if (logger.isDebugEnabled())
        logger.debug("Authenticating the current user using session based Ticket information.");
    // retrieve the User object
    User user = getUser(sc, req, res);
    HttpSession session = req.getSession();
    // get the login bean if we're not in the portal
    LoginBean loginBean = null;
    if (Application.inPortalServer() == false) {
        if (logger.isDebugEnabled())
            logger.debug("We're not in the portal, getting the login bean.");
        loginBean = (LoginBean) session.getAttribute(LOGIN_BEAN);
    }
    // setup the authentication context
    WebApplicationContext wc = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
    AuthenticationService auth = (AuthenticationService) wc.getBean(AUTHENTICATION_SERVICE);
    if (logger.isDebugEnabled())
        logger.debug("Force guest is: " + forceGuest);
    if (user == null || forceGuest) {
        if (logger.isDebugEnabled())
            logger.debug("The user is null.");
        // the last stored username string is cleared.
        if (session.getAttribute(AuthenticationHelper.SESSION_INVALIDATED) == null) {
            if (logger.isDebugEnabled())
                logger.debug("The session is not invalidated.");
            Cookie authCookie = getAuthCookie(req);
            if (allowGuest == true && (authCookie == null || forceGuest)) {
                if (logger.isDebugEnabled())
                    logger.debug("No previous authentication or forced Guest - attempt Guest access.");
                try {
                    auth.authenticateAsGuest();
                    // if we get here then Guest access was allowed and successful
                    setUser(sc, req, AuthenticationUtil.getGuestUserName(), auth.getCurrentTicket(), false);
                    // Set up the thread context
                    setupThread(sc, req, res, true);
                    // remove the session invalidated flag
                    session.removeAttribute(AuthenticationHelper.SESSION_INVALIDATED);
                    if (logger.isDebugEnabled())
                        logger.debug("Successfully authenticated as guest.");
                    // it is the responsibilty of the caller to handle the Guest return status
                    return AuthenticationStatus.Guest;
                } catch (AuthenticationException guestError) {
                    if (logger.isDebugEnabled())
                        logger.debug("An AuthenticationException occurred, expected if Guest access not allowed - continue to login page as usual", guestError);
                } catch (AccessDeniedException accessError) {
                    // Guest is unable to access either properties on Person
                    AuthenticationService unprotAuthService = (AuthenticationService) wc.getBean(UNPROTECTED_AUTH_SERVICE);
                    unprotAuthService.invalidateTicket(unprotAuthService.getCurrentTicket());
                    unprotAuthService.clearCurrentSecurityContext();
                    logger.warn("Unable to login as Guest: ", accessError);
                } catch (Throwable e) {
                    // Some other kind of serious failure to report
                    AuthenticationService unprotAuthService = (AuthenticationService) wc.getBean(UNPROTECTED_AUTH_SERVICE);
                    unprotAuthService.invalidateTicket(unprotAuthService.getCurrentTicket());
                    unprotAuthService.clearCurrentSecurityContext();
                    throw new AlfrescoRuntimeException("Failed to authenticate as Guest user.", e);
                }
            }
        }
        if (logger.isDebugEnabled())
            logger.debug("Session invalidated - return to login screen.");
        return AuthenticationStatus.Failure;
    } else {
        if (logger.isDebugEnabled())
            logger.debug("The user is: " + user.getUserName());
        // set last authentication username cookie value
        String loginName;
        if (loginBean != null && (loginName = loginBean.getUsernameInternal()) != null) {
            if (logger.isDebugEnabled())
                logger.debug("Set last authentication username cookie value");
            setUsernameCookie(req, res, loginName);
        }
        // Set up the thread context
        setupThread(sc, req, res, true);
        return AuthenticationStatus.Success;
    }
}
Also used : Cookie(javax.servlet.http.Cookie) AccessDeniedException(org.alfresco.repo.security.permissions.AccessDeniedException) SessionUser(org.alfresco.repo.SessionUser) User(org.alfresco.web.bean.repository.User) AuthenticationException(org.alfresco.repo.security.authentication.AuthenticationException) HttpSession(javax.servlet.http.HttpSession) LoginBean(org.alfresco.web.bean.LoginBean) AlfrescoRuntimeException(org.alfresco.error.AlfrescoRuntimeException) AuthenticationService(org.alfresco.service.cmr.security.AuthenticationService) WebApplicationContext(org.springframework.web.context.WebApplicationContext)

Aggregations

AuthenticationService (org.alfresco.service.cmr.security.AuthenticationService)8 SessionUser (org.alfresco.repo.SessionUser)6 WebApplicationContext (org.springframework.web.context.WebApplicationContext)6 AuthenticationException (org.alfresco.repo.security.authentication.AuthenticationException)5 User (org.alfresco.web.bean.repository.User)5 HttpSession (javax.servlet.http.HttpSession)4 IOException (java.io.IOException)2 PortletException (javax.portlet.PortletException)2 PortletSession (javax.portlet.PortletSession)2 NodeService (org.alfresco.service.cmr.repository.NodeService)2 PersonService (org.alfresco.service.cmr.security.PersonService)2 LoginBean (org.alfresco.web.bean.LoginBean)2 File (java.io.File)1 Serializable (java.io.Serializable)1 HashMap (java.util.HashMap)1 PortletRequestDispatcher (javax.portlet.PortletRequestDispatcher)1 Cookie (javax.servlet.http.Cookie)1 HttpServletRequest (javax.servlet.http.HttpServletRequest)1 AlfrescoRuntimeException (org.alfresco.error.AlfrescoRuntimeException)1 AuthenticationComponent (org.alfresco.repo.security.authentication.AuthenticationComponent)1