Search in sources :

Example 1 with ISecurityContext

use of org.apereo.portal.security.ISecurityContext in project uPortal by Jasig.

the class RemoteUserPersonManager method getPerson.

/**
     * Retrieve an IPerson object for the incoming request
     *
     * @param request
     * @return IPerson object for the incoming request
     * @exception PortalSecurityException Description of the Exception
     */
public IPerson getPerson(HttpServletRequest request) throws PortalSecurityException {
    // Return the person object if it exists in the user's session
    final HttpSession session = request.getSession(false);
    IPerson person = null;
    if (session != null) {
        person = (IPerson) session.getAttribute(PERSON_SESSION_KEY);
        if (person != null) {
            return person;
        }
    }
    try {
        // Create a new instance of a person
        person = createGuestPerson(request);
        // If the user has authenticated with the server which has implemented web authentication,
        // the REMOTE_USER environment variable will be set.
        String remoteUser = request.getRemoteUser();
        // We don't want to ignore the security contexts which are already configured in security.properties, so we
        // retrieve the existing security contexts.  If one of the existing security contexts is a RemoteUserSecurityContext,
        // we set the REMOTE_USER field of the existing RemoteUserSecurityContext context.
        //
        // If a RemoteUserSecurityContext does not already exist, we create one and populate the REMOTE_USER field.
        ISecurityContext context = null;
        Enumeration subContexts = null;
        boolean remoteUserSecurityContextExists = false;
        // Retrieve existing security contexts.
        context = person.getSecurityContext();
        if (context != null)
            subContexts = context.getSubContexts();
        if (subContexts != null) {
            while (subContexts.hasMoreElements()) {
                ISecurityContext ctx = (ISecurityContext) subContexts.nextElement();
                // Check to see if a RemoteUserSecurityContext already exists, and set the REMOTE_USER
                if (ctx instanceof RemoteUserSecurityContext) {
                    RemoteUserSecurityContext remoteuserctx = (RemoteUserSecurityContext) ctx;
                    remoteuserctx.setRemoteUser(remoteUser);
                    remoteUserSecurityContextExists = true;
                }
            }
        }
        // This preserves the default behavior of this class.
        if (!remoteUserSecurityContextExists) {
            RemoteUserSecurityContext remoteuserctx = new RemoteUserSecurityContext(remoteUser);
            person.setSecurityContext(remoteuserctx);
        }
    } catch (Exception e) {
        // Log the exception
        log.error("Exception creating person for request " + request, e);
    }
    if (session != null) {
        // Add this person object to the user's session
        session.setAttribute(PERSON_SESSION_KEY, person);
    }
    // Return the new person object
    return (person);
}
Also used : IPerson(org.apereo.portal.security.IPerson) Enumeration(java.util.Enumeration) HttpSession(javax.servlet.http.HttpSession) ISecurityContext(org.apereo.portal.security.ISecurityContext) PortalSecurityException(org.apereo.portal.security.PortalSecurityException)

Example 2 with ISecurityContext

use of org.apereo.portal.security.ISecurityContext in project uPortal by Jasig.

the class LogoutController method getRedirectionUrl.

/**
     * The redirect is determined based upon the context that passed authentication The
     * LogoutController looks at each authenticated context and determines if a redirect exists for
     * that context in the redirectMap variable (loaded from security.properties file). The redirect
     * is returned for the first authenticated context that has an associated redirect string. If
     * such a context is not found, we use the default DEFAULT_REDIRECT that was originally setup.
     *
     * <p>NOTE: This will work or not work based upon the logic in the root context. At this time,
     * all known security contexts extend the ChainingSecurityContext class. If a context has the
     * variable stopWhenAuthenticated set to false, the user may be logged into multiple security
     * contexts. If this is the case, the logout process currently implemented does not accommodate
     * multiple logouts. As a reference implemention, the current implementation assumes only one
     * security context has been authenticated. Modifications to perform multiple logouts should be
     * considered when a concrete need arises and can be handled by this class or through a change
     * in the ISecurityConext API where a context knows how to perform it's own logout.
     *
     * @param request
     * @return String representing the redirection URL
     */
private String getRedirectionUrl(HttpServletRequest request) {
    String redirect = null;
    final String defaultRedirect = request.getContextPath() + "/";
    IPerson person = null;
    if (this.redirectMap == null) {
        return defaultRedirect;
    }
    try {
        // Get the person object associated with the request
        person = this.personManager.getPerson(request);
        if (person != null) {
            // Retrieve the security context for the user
            final ISecurityContext securityContext = person.getSecurityContext();
            if (securityContext.isAuthenticated()) {
                if (log.isDebugEnabled()) {
                    log.debug("LogoutController::getRedirectionUrl()" + " Looking for redirect string for the root context");
                }
                redirect = this.redirectMap.get("root");
                if (redirect != null && !redirect.equals("")) {
                    return redirect;
                }
            }
            final Enumeration subCtxNames = securityContext.getSubContextNames();
            while (subCtxNames.hasMoreElements()) {
                final String subCtxName = (String) subCtxNames.nextElement();
                if (log.isDebugEnabled()) {
                    log.debug("LogoutController::getRedirectionUrl() " + " subCtxName = " + subCtxName);
                }
                // strip off "root." part of name
                final ISecurityContext sc = securityContext.getSubContext(subCtxName);
                if (log.isDebugEnabled()) {
                    log.debug("LogoutController::getRedirectionUrl()" + " subCtxName isAuth = " + sc.isAuthenticated());
                }
                if (sc.isAuthenticated()) {
                    if (log.isDebugEnabled()) {
                        log.debug("LogoutController::getRedirectionUrl()" + " Looking for redirect string for subCtxName = " + subCtxName);
                    }
                    redirect = this.redirectMap.get(subCtxName);
                    if (redirect != null && !redirect.equals("")) {
                        if (log.isDebugEnabled()) {
                            log.debug("LogoutController::getRedirectionUrl()" + " subCtxName redirect = " + redirect);
                        }
                        break;
                    }
                }
            }
        }
    } catch (final Exception e) {
        // Log the exception
        log.error("LogoutController::getRedirectionUrl() Error:", e);
    }
    if (redirect == null) {
        redirect = defaultRedirect;
    }
    if (log.isDebugEnabled()) {
        log.debug("LogoutController::getRedirectionUrl()" + " redirectionURL = " + redirect);
    }
    return redirect;
}
Also used : IPerson(org.apereo.portal.security.IPerson) Enumeration(java.util.Enumeration) ISecurityContext(org.apereo.portal.security.ISecurityContext) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) PortalException(org.apereo.portal.PortalException)

Example 3 with ISecurityContext

use of org.apereo.portal.security.ISecurityContext in project uPortal by Jasig.

the class Authentication method authenticate.

/**
     * Attempts to authenticate a given IPerson based on a set of principals and credentials
     *
     * @param principals
     * @param credentials
     * @param person
     * @exception PortalSecurityException
     */
public void authenticate(HttpServletRequest request, Map<String, String> principals, Map<String, String> credentials, IPerson person) throws PortalSecurityException {
    // Retrieve the security context for the user
    final ISecurityContext securityContext = person.getSecurityContext();
    //Set the principals and credentials for the security context chain
    this.configureSecurityContextChain(principals, credentials, person, securityContext, BASE_CONTEXT_NAME);
    // NOTE: PortalPreAuthenticatedProcessingFilter looks in the security.properties file to
    // determine what tokens to look for that represent the principals and
    // credentials for each context. It then retrieves the values from the request
    // and stores the values in the principals and credentials HashMaps that are
    // passed to the Authentication service.
    // Attempt to authenticate the user
    final long start = System.currentTimeMillis();
    securityContext.authenticate();
    final long elapsed = System.currentTimeMillis() - start;
    // Check to see if the user was authenticated
    if (securityContext.isAuthenticated()) {
        // metric
        lastAuthentication = authenticationTimes.add(elapsed);
        // Add the authenticated username to the person object
        // the login name may have been provided or reset by the security provider
        // so this needs to be done after authentication.
        final String userName = securityContext.getPrincipal().getUID();
        person.setAttribute(IPerson.USERNAME, userName);
        if (log.isDebugEnabled()) {
            log.debug("FINISHED SecurityContext authentication for user '" + userName + "' in " + elapsed + "ms #milestone");
        }
        threadNamingRequestFilter.updateCurrentUsername(userName);
        /*
             * Clear cached group info for this user.
             *
             * There seem to be 2 systems in place for this information:
             *   - The old system based on EntityCachingService
             *   - The new system based on ehcache
             *
             * For uPortal 5, we should work to remove the old system.
             */
        // Old system
        GroupService.finishedSession(person);
        for (IAuthenticationListener authListener : authenticationListeners) {
            // New system
            authListener.userAuthenticated(person);
        }
        //Clear all existing cached data about the person
        this.usernameTaggedCacheEntryPurger.purgeTaggedCacheEntries(userName);
        // Retrieve the additional descriptor from the security context
        final IAdditionalDescriptor addInfo = person.getSecurityContext().getAdditionalDescriptor();
        // Process the additional descriptor if one was created
        if (addInfo != null) {
            //       handled by the PersonManager.
            if (addInfo instanceof IPerson) {
                final IPerson newPerson = (IPerson) addInfo;
                person.setFullName(newPerson.getFullName());
                for (final String attributeName : newPerson.getAttributeMap().keySet()) {
                    person.setAttribute(attributeName, newPerson.getAttribute(attributeName));
                }
                this.resetEntityIdentifier(person, newPerson);
            } else // simply copy all of these additional attributes into the IPerson
            if (addInfo instanceof Map) {
                // Cast the additional descriptor as a Map
                final Map<?, ?> additionalAttributes = (Map<?, ?>) addInfo;
                // Copy each additional attribute into the person object
                for (final Iterator<?> keys = additionalAttributes.keySet().iterator(); keys.hasNext(); ) {
                    // Get a key
                    final String key = (String) keys.next();
                    // Set the attribute
                    person.setAttribute(key, additionalAttributes.get(key));
                }
            } else if (addInfo instanceof ChainingSecurityContext.ChainingAdditionalDescriptor) {
            // do nothing
            } else {
                if (log.isWarnEnabled()) {
                    log.warn("Authentication Service received unknown additional descriptor [" + addInfo + "]");
                }
            }
        }
        // Populate the person object using the PersonDirectory if applicable
        if (PropertiesManager.getPropertyAsBoolean("org.apereo.portal.services.Authentication.usePersonDirectory")) {
            // Retrieve all of the attributes associated with the person logging in
            final String username = person.getUserName();
            final long timestamp = System.currentTimeMillis();
            if (log.isDebugEnabled()) {
                log.debug("STARTING user attribute gathering for user '" + userName + "' #milestone");
            }
            final IPersonAttributes personAttributes = this.personAttributeDao.getPerson(username);
            if (log.isDebugEnabled()) {
                log.debug("FINISHED user attribute gathering for user '" + userName + "' in " + Long.toString(System.currentTimeMillis() - timestamp) + "ms #milestone");
            }
            if (personAttributes != null) {
                // attribs may be null.  IPersonAttributeDao returns null when it does not recognize a user at all, as
                // distinguished from returning an empty Map of attributes when it recognizes a user has having no
                // attributes.
                person.setAttributes(personAttributes.getAttributes());
            }
        }
        // Make sure the the user's fullname is set
        if (person.getFullName() == null) {
            // Use portal display name if one exists
            if (person.getAttribute("portalDisplayName") != null) {
                person.setFullName((String) person.getAttribute("portalDisplayName"));
            } else // If not try the eduPerson displayName
            if (person.getAttribute("displayName") != null) {
                person.setFullName((String) person.getAttribute("displayName"));
            }
            // If still no FullName use an unrecognized string
            if (person.getFullName() == null) {
                person.setFullName("Unrecognized person: " + person.getAttribute(IPerson.USERNAME));
            }
        }
        // Find the uPortal userid for this user or flunk authentication if not found
        // The template username should actually be derived from directory information.
        // The reference implementation sets the uPortalTemplateUserName to the default in
        // the portal.properties file.
        // A more likely template would be staff or faculty or undergraduate.
        final boolean autocreate = PropertiesManager.getPropertyAsBoolean("org.apereo.portal.services.Authentication.autoCreateUsers");
        // If we are going to be auto creating accounts then we must find the default template to use
        if (autocreate && person.getAttribute("uPortalTemplateUserName") == null) {
            final String defaultTemplateUserName = PropertiesManager.getProperty("org.apereo.portal.services.Authentication.defaultTemplateUserName");
            person.setAttribute("uPortalTemplateUserName", defaultTemplateUserName);
        }
        try {
            // Attempt to retrieve the UID
            final int newUID = this.userIdentityStore.getPortalUID(person, autocreate);
            person.setID(newUID);
        } catch (final AuthorizationException ae) {
            log.error("Exception retrieving ID", ae);
            throw new PortalSecurityException("Authentication Service: Exception retrieving UID");
        }
    }
    //Publish a login event for the person
    this.portalEventFactory.publishLoginEvent(request, this, person);
}
Also used : IAdditionalDescriptor(org.apereo.portal.security.IAdditionalDescriptor) AuthorizationException(org.apereo.portal.AuthorizationException) ISecurityContext(org.apereo.portal.security.ISecurityContext) PortalSecurityException(org.apereo.portal.security.PortalSecurityException) IPerson(org.apereo.portal.security.IPerson) IPersonAttributes(org.jasig.services.persondir.IPersonAttributes) Iterator(java.util.Iterator) Map(java.util.Map)

Example 4 with ISecurityContext

use of org.apereo.portal.security.ISecurityContext in project uPortal by Jasig.

the class RestrictedPersonTest method testSetSecurityContext.

/** Test that setSecurityContext does not change the security context. */
public void testSetSecurityContext() {
    ISecurityContext baselineContext = this.person.getSecurityContext();
    assertNotNull(baselineContext);
    assertNull(this.restrictedPerson.getSecurityContext());
    this.restrictedPerson.setSecurityContext(new DummySecurityContext());
    assertNull(this.restrictedPerson.getSecurityContext());
    assertSame(baselineContext, this.person.getSecurityContext());
}
Also used : ISecurityContext(org.apereo.portal.security.ISecurityContext)

Example 5 with ISecurityContext

use of org.apereo.portal.security.ISecurityContext in project uPortal by Jasig.

the class PortalPreAuthenticatedProcessingFilterTest method testGetAuthenticatedCredentials.

@Test
public void testGetAuthenticatedCredentials() {
    ISecurityContext creds = (ISecurityContext) filter.getPreAuthenticatedCredentials(request);
    assertEquals(context, creds);
}
Also used : ISecurityContext(org.apereo.portal.security.ISecurityContext) Test(org.junit.Test)

Aggregations

ISecurityContext (org.apereo.portal.security.ISecurityContext)14 IPerson (org.apereo.portal.security.IPerson)8 Enumeration (java.util.Enumeration)5 PortalSecurityException (org.apereo.portal.security.PortalSecurityException)3 HttpServletRequest (javax.servlet.http.HttpServletRequest)2 HttpSession (javax.servlet.http.HttpSession)2 IAuthorizationPrincipal (org.apereo.portal.security.IAuthorizationPrincipal)2 IUserInstance (org.apereo.portal.user.IUserInstance)2 IOException (java.io.IOException)1 MalformedURLException (java.net.MalformedURLException)1 URL (java.net.URL)1 HashMap (java.util.HashMap)1 Iterator (java.util.Iterator)1 Map (java.util.Map)1 ServletException (javax.servlet.ServletException)1 AuthorizationException (org.apereo.portal.AuthorizationException)1 PortalException (org.apereo.portal.PortalException)1 IPortletDefinition (org.apereo.portal.portlet.om.IPortletDefinition)1 IAdditionalDescriptor (org.apereo.portal.security.IAdditionalDescriptor)1 IOpaqueCredentials (org.apereo.portal.security.IOpaqueCredentials)1