Search in sources :

Example 6 with PortalSecurityException

use of org.apereo.portal.security.PortalSecurityException 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");
        // 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.apereo.services.persondir.IPersonAttributes) Iterator(java.util.Iterator) Map(java.util.Map)

Example 7 with PortalSecurityException

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

the class AuthorizationTester method initializeAuthorizationService.

/** Create an implementation of IAuthorizationService. */
private void initializeAuthorizationService() throws AuthorizationException {
    // Get the security properties file
    java.io.InputStream secprops = AuthorizationService.class.getResourceAsStream("/properties/security.properties");
    // Get the properties from the security properties file
    Properties pr = new Properties();
    String s_factoryName = null;
    try {
        pr.load(secprops);
        // Look for our authorization factory and instantiate an instance of it or die trying.
        if ((s_factoryName = pr.getProperty("authorizationProvider")) == null) {
            print("ERROR: AuthorizationProvider not specified or incorrect in security.properties");
        } else {
            try {
                IAuthorizationServiceFactory factory = (IAuthorizationServiceFactory) Class.forName(s_factoryName).newInstance();
                authorizationService = factory.getAuthorization();
            } catch (Exception e) {
                print("ERROR: Failed to instantiate " + s_factoryName);
            }
        }
    } catch (IOException e) {
        print("ERROR: " + e.getMessage());
    } finally {
        try {
            if (secprops != null)
                secprops.close();
        } catch (IOException ioe) {
            print(new PortalSecurityException(ioe.getMessage()).toString());
        }
    }
}
Also used : IAuthorizationServiceFactory(org.apereo.portal.security.IAuthorizationServiceFactory) IOException(java.io.IOException) Properties(java.util.Properties) PortalSecurityException(org.apereo.portal.security.PortalSecurityException) IOException(java.io.IOException) AuthorizationException(org.apereo.portal.AuthorizationException) PortalSecurityException(org.apereo.portal.security.PortalSecurityException)

Example 8 with PortalSecurityException

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

the class TrustSecurityContext method authenticate.

public synchronized void authenticate() throws PortalSecurityException {
    this.isauth = true;
    if (this.myPrincipal.UID != null) {
        try {
            String first_name, last_name;
            ILocalAccountDao accountStore = LocalAccountDaoLocator.getLocalAccountDao();
            ILocalAccountPerson account = accountStore.getPerson(this.myPrincipal.UID);
            if (account != null) {
                first_name = (String) account.getAttributeValue("given");
                last_name = (String) account.getAttributeValue("sn");
                this.myPrincipal.FullName = first_name + " " + last_name;
                if (log.isInfoEnabled())
                    log.info("User " + this.myPrincipal.UID + " is authenticated");
                this.isauth = true;
            } else {
                if (log.isInfoEnabled())
                    log.info("No such user: " + this.myPrincipal.UID);
            }
        } catch (Exception e) {
            PortalSecurityException ep = new PortalSecurityException("SQL Database Error");
            log.error(e, e);
            throw (ep);
        }
    } else {
        log.error("Principal not initialized prior to authenticate");
    }
    // Ok...we are now ready to authenticate all of our subcontexts.
    super.authenticate();
    return;
}
Also used : ILocalAccountDao(org.apereo.portal.persondir.ILocalAccountDao) ILocalAccountPerson(org.apereo.portal.persondir.ILocalAccountPerson) PortalSecurityException(org.apereo.portal.security.PortalSecurityException) PortalSecurityException(org.apereo.portal.security.PortalSecurityException)

Example 9 with PortalSecurityException

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

the class UserInstanceManagerImpl method getUserInstance.

/**
 * Returns the UserInstance object that is associated with the given request.
 *
 * @param request Incoming HttpServletRequest
 * @return UserInstance object associated with the given request
 */
@Override
public IUserInstance getUserInstance(HttpServletRequest request) throws PortalException {
    try {
        request = this.portalRequestUtils.getOriginalPortalRequest(request);
    } catch (IllegalArgumentException iae) {
    // ignore, just means that this isn't a wrapped request
    }
    // Use request attributes first for the fastest possible retrieval
    IUserInstance userInstance = (IUserInstance) request.getAttribute(KEY);
    if (userInstance != null) {
        return userInstance;
    }
    final IPerson person;
    try {
        // Retrieve the person object that is associated with the request
        person = this.personManager.getPerson(request);
    } catch (Exception e) {
        logger.error("Exception while retrieving IPerson!", e);
        throw new PortalSecurityException("Could not retrieve IPerson", e);
    }
    if (person == null) {
        throw new PortalSecurityException("PersonManager returned null person for this request.  With no user, there's no UserInstance.  Is PersonManager misconfigured?  RDBMS access misconfigured?");
    }
    final HttpSession session = request.getSession();
    if (session == null) {
        throw new IllegalStateException("HttpServletRequest.getSession() returned a null session for request: " + request);
    }
    // Return the UserInstance object if it's in the session
    UserInstanceHolder userInstanceHolder = getUserInstanceHolder(session);
    if (userInstanceHolder != null) {
        userInstance = userInstanceHolder.getUserInstance();
        if (userInstance != null) {
            return userInstance;
        }
    }
    // Create either a UserInstance or a GuestUserInstance
    final LocaleManager localeManager = this.getLocaleManager(request, person);
    final String userAgent = this.getUserAgent(request);
    final IUserProfile userProfile = this.getUserProfile(request, person, localeManager, userAgent);
    // Create the user layout manager and user instance object
    IUserLayoutManager userLayoutManager = userLayoutManagerFactory.getUserLayoutManager(person, userProfile);
    final UserPreferencesManager userPreferencesManager = new UserPreferencesManager(person, userProfile, userLayoutManager);
    userInstance = new UserInstance(person, userPreferencesManager, localeManager);
    // Ensure the newly created UserInstance is cached in the session
    if (userInstanceHolder == null) {
        userInstanceHolder = new UserInstanceHolder();
    }
    userInstanceHolder.setUserInstance(userInstance);
    session.setAttribute(KEY, userInstanceHolder);
    request.setAttribute(KEY, userInstance);
    // Return the new UserInstance
    return userInstance;
}
Also used : HttpSession(javax.servlet.http.HttpSession) PortalSecurityException(org.apereo.portal.security.PortalSecurityException) PortalSecurityException(org.apereo.portal.security.PortalSecurityException) PortalException(org.apereo.portal.PortalException) UserPreferencesManager(org.apereo.portal.UserPreferencesManager) IPerson(org.apereo.portal.security.IPerson) IUserProfile(org.apereo.portal.IUserProfile) LocaleManager(org.apereo.portal.i18n.LocaleManager) UserInstance(org.apereo.portal.UserInstance) IUserLayoutManager(org.apereo.portal.layout.IUserLayoutManager)

Example 10 with PortalSecurityException

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

the class BasePersonManager method getPerson.

/**
 * This is a basic implementation of <code>getPerson</code> that formerly appeared in <code>
 * SimplePersonManager</code>. For uPortal 5, it's better to avoid unnecessary bean tweaking on
 * the part of deployers, so the various flavors of PersonManager were combined in a manner
 * where the appropriate behavior triggers automatically (based on AuthN settings).
 *
 * @param request the servlet request object
 * @return the IPerson object for the incoming request
 */
@Override
public IPerson getPerson(HttpServletRequest request) throws PortalSecurityException {
    HttpSession session = request.getSession(false);
    IPerson person = null;
    // Return the person object if it exists in the user's session
    if (session != null) {
        person = (IPerson) session.getAttribute(PERSON_SESSION_KEY);
        logger.debug("getPerson -- person object retrieved from session is [{}]", person);
    }
    if (person == null) {
        try {
            // Create a guest person
            person = createGuestPerson(request);
            logger.debug("getPerson -- created a new guest person [{}]", person);
        } catch (Exception e) {
            // Log the exception
            logger.error("Exception creating guest person.", e);
        }
        // Add this person object to the user's session
        if (person != null && session != null) {
            session.setAttribute(PERSON_SESSION_KEY, person);
        }
    }
    return person;
}
Also used : IPerson(org.apereo.portal.security.IPerson) HttpSession(javax.servlet.http.HttpSession) PortalSecurityException(org.apereo.portal.security.PortalSecurityException)

Aggregations

PortalSecurityException (org.apereo.portal.security.PortalSecurityException)12 IPerson (org.apereo.portal.security.IPerson)6 HttpSession (javax.servlet.http.HttpSession)5 ISecurityContext (org.apereo.portal.security.ISecurityContext)3 Enumeration (java.util.Enumeration)2 AuthorizationException (org.apereo.portal.AuthorizationException)2 ILocalAccountDao (org.apereo.portal.persondir.ILocalAccountDao)2 ILocalAccountPerson (org.apereo.portal.persondir.ILocalAccountPerson)2 IOException (java.io.IOException)1 Iterator (java.util.Iterator)1 Map (java.util.Map)1 Properties (java.util.Properties)1 AuthenticationException (javax.naming.AuthenticationException)1 NamingEnumeration (javax.naming.NamingEnumeration)1 NamingException (javax.naming.NamingException)1 Attributes (javax.naming.directory.Attributes)1 DirContext (javax.naming.directory.DirContext)1 SearchControls (javax.naming.directory.SearchControls)1 SearchResult (javax.naming.directory.SearchResult)1 IUserProfile (org.apereo.portal.IUserProfile)1