Search in sources :

Example 6 with IPersonAttributes

use of org.jasig.services.persondir.IPersonAttributes 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 7 with IPersonAttributes

use of org.jasig.services.persondir.IPersonAttributes in project uPortal by Jasig.

the class AuthorizationHeaderProvider method createHeader.

@Override
public Header createHeader(RenderRequest renderRequest, RenderResponse renderResponse) {
    // Username
    final String username = getUsername(renderRequest);
    // Attributes
    final Map<String, List<String>> attributes = new HashMap<>();
    final IPersonAttributes person = personAttributeDao.getPerson(username);
    if (person != null) {
        for (Entry<String, List<Object>> y : person.getAttributes().entrySet()) {
            final List<String> values = new ArrayList<>();
            for (Object value : y.getValue()) {
                if (value instanceof String) {
                    values.add((String) value);
                }
            }
            attributes.put(y.getKey(), values);
        }
    }
    logger.debug("Found the following user attributes for username='{}':  {}", username, attributes);
    // Groups
    final List<String> groups = new ArrayList<>();
    final IGroupMember groupMember = GroupService.getGroupMember(username, IPerson.class);
    if (groupMember != null) {
        Set<IEntityGroup> ancestors = groupMember.getAncestorGroups();
        for (IEntityGroup g : ancestors) {
            groups.add(g.getName());
        }
    }
    logger.debug("Found the following group affiliations for username='{}':  {}", username, groups);
    // Expiration of the Bearer token
    final PortletSession portletSession = renderRequest.getPortletSession();
    final Date expires = new Date(portletSession.getLastAccessedTime() + ((long) portletSession.getMaxInactiveInterval() * 1000L));
    // Authorization header
    final Bearer bearer = bearerService.createBearer(username, attributes, groups, expires);
    final Header rslt = new BasicHeader(Headers.AUTHORIZATION.getName(), Headers.BEARER_TOKEN_PREFIX + bearer.getEncryptedToken());
    logger.debug("Produced the following Authorization header for username='{}':  {}", username, rslt);
    return rslt;
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Date(java.util.Date) IEntityGroup(org.apereo.portal.groups.IEntityGroup) IGroupMember(org.apereo.portal.groups.IGroupMember) IPersonAttributes(org.jasig.services.persondir.IPersonAttributes) PortletSession(javax.portlet.PortletSession) Header(org.apache.http.Header) BasicHeader(org.apache.http.message.BasicHeader) ArrayList(java.util.ArrayList) List(java.util.List) Bearer(org.apereo.portal.soffit.model.v1_0.Bearer) BasicHeader(org.apache.http.message.BasicHeader)

Example 8 with IPersonAttributes

use of org.jasig.services.persondir.IPersonAttributes in project uPortal by Jasig.

the class AttributeSwapperHelperImpl method getSwappableAttributes.

/* (non-Javadoc)
     * @see org.apereo.portal.portlets.swapper.IAttributeSwapperHelper#getSwappableAttributes(org.springframework.webflow.context.ExternalContext)
     */
public Set<String> getSwappableAttributes(ExternalContext externalContext) {
    final PortletRequest portletRequest = (PortletRequest) externalContext.getNativeRequest();
    final PortletPreferences preferences = portletRequest.getPreferences();
    final Set<String> swappableAttributes;
    //Use prefs configured list if available
    final String[] configuredAttributes = preferences.getValues(ATTRIBUTE_SWAPPER_ATTRIBUTES_FORM_SWAPPABLE_ATTRIBUTES, null);
    final String[] excludedAttributes = preferences.getValues(ATTRIBUTE_SWAPPER_ATTRIBUTES_FORM_SWAPPABLE_ATTRIBUTES_EXCLUDES, null);
    if (configuredAttributes != null) {
        swappableAttributes = new LinkedHashSet<String>(Arrays.asList(configuredAttributes));
    } else {
        //If no prefs try the 'possibleUserAttributeNames' from the IPersonAttributeDao
        final Set<String> possibleAttributes = this.overwritingPersonAttributeDao.getPossibleUserAttributeNames();
        if (possibleAttributes != null) {
            swappableAttributes = new TreeSet<String>(possibleAttributes);
        } else //If no possible names try getting the current user's attributes and use the key set
        {
            final Principal currentUser = externalContext.getCurrentUser();
            final IPersonAttributes baseUserAttributes = this.getOriginalUserAttributes(currentUser.getName());
            if (baseUserAttributes != null) {
                final Map<String, List<Object>> attributes = baseUserAttributes.getAttributes();
                swappableAttributes = new LinkedHashSet<String>(attributes.keySet());
            } else {
                swappableAttributes = Collections.emptySet();
            }
        }
    }
    if (excludedAttributes != null) {
        for (final String excludedAttribute : excludedAttributes) {
            swappableAttributes.remove(excludedAttribute);
        }
    }
    return swappableAttributes;
}
Also used : PortletRequest(javax.portlet.PortletRequest) IPersonAttributes(org.jasig.services.persondir.IPersonAttributes) PortletPreferences(javax.portlet.PortletPreferences) List(java.util.List) Principal(java.security.Principal)

Example 9 with IPersonAttributes

use of org.jasig.services.persondir.IPersonAttributes in project uPortal by Jasig.

the class AttributeSwapperHelperImpl method resetAttributes.

/* (non-Javadoc)
     * @see org.apereo.portal.portlets.swapper.IAttributeSwapperHelper#resetAttributes(java.lang.String)
     */
public void resetAttributes(ExternalContext externalContext) {
    final Principal currentUser = externalContext.getCurrentUser();
    final String uid = currentUser.getName();
    this.logger.warn("User '" + uid + "' reseting to default attributes");
    //Remove the person directory override
    this.overwritingPersonAttributeDao.removeUserAttributeOverride(uid);
    //Remove the IPerson attribute override, bit of a hack as we really just remove all overrides
    //then re-add all attributes from person directory
    final PortletRequest portletRequest = (PortletRequest) externalContext.getNativeRequest();
    final HttpServletRequest portalRequest = this.portalRequestUtils.getPortletHttpRequest(portletRequest);
    final IPerson person = this.personManager.getPerson(portalRequest);
    final Set<String> overriddenAttributes = (Set<String>) person.getAttribute(OVERRIDDEN_ATTRIBUTES);
    if (overriddenAttributes != null) {
        person.setAttribute(OVERRIDDEN_ATTRIBUTES, null);
        for (final String attribute : overriddenAttributes) {
            person.setAttribute(attribute, null);
        }
    }
    final IPersonAttributes originalUserAttributes = this.getOriginalUserAttributes(uid);
    final Map<String, List<Object>> attributes = originalUserAttributes.getAttributes();
    person.setAttributes(attributes);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) IPerson(org.apereo.portal.security.IPerson) PortletRequest(javax.portlet.PortletRequest) TreeSet(java.util.TreeSet) LinkedHashSet(java.util.LinkedHashSet) Set(java.util.Set) IPersonAttributes(org.jasig.services.persondir.IPersonAttributes) List(java.util.List) Principal(java.security.Principal)

Example 10 with IPersonAttributes

use of org.jasig.services.persondir.IPersonAttributes in project uPortal by Jasig.

the class AttributeSwapperHelperImpl method swapAttributes.

/* (non-Javadoc)
     * @see org.apereo.portal.portlets.swapper.IAttributeSwapperHelper#swapAttributes(org.springframework.webflow.context.ExternalContext, org.apereo.portal.portlets.swapper.AttributeSwapRequest)
     */
public void swapAttributes(ExternalContext externalContext, AttributeSwapRequest attributeSwapRequest) {
    //Collate the swap request into a single overrides map
    final Map<String, Object> attributes = new HashMap<String, Object>();
    final Map<String, Attribute> currentAttributes = attributeSwapRequest.getCurrentAttributes();
    this.copyAttributes(attributes, currentAttributes);
    final Map<String, Attribute> attributesToCopy = attributeSwapRequest.getAttributesToCopy();
    this.copyAttributes(attributes, attributesToCopy);
    final Principal currentUser = externalContext.getCurrentUser();
    final String uid = currentUser.getName();
    final IPersonAttributes originalUserAttributes = this.getOriginalUserAttributes(uid);
    //Filter out unchanged attributes
    for (final Iterator<Map.Entry<String, Object>> overrideAttrEntryItr = attributes.entrySet().iterator(); overrideAttrEntryItr.hasNext(); ) {
        final Entry<String, Object> overrideAttrEntry = overrideAttrEntryItr.next();
        final String attribute = overrideAttrEntry.getKey();
        final Object originalValue = originalUserAttributes.getAttributeValue(attribute);
        final Object overrideValue = overrideAttrEntry.getValue();
        if (originalValue == overrideValue || (originalValue != null && originalValue.equals(overrideValue))) {
            overrideAttrEntryItr.remove();
        }
    }
    final PortletRequest portletRequest = (PortletRequest) externalContext.getNativeRequest();
    final PortletPreferences preferences = portletRequest.getPreferences();
    final String[] configuredAttributes = preferences.getValues(ATTRIBUTE_SWAPPER_ATTRIBUTES_FORM_SWAPPABLE_ATTRIBUTES, null);
    final String[] excludedAttributes = preferences.getValues(ATTRIBUTE_SWAPPER_ATTRIBUTES_FORM_SWAPPABLE_ATTRIBUTES_EXCLUDES, null);
    //Calculate the Set of attributes that are OK to be swapped
    final Set<String> allowedAttributes = new LinkedHashSet<String>();
    if (configuredAttributes != null) {
        allowedAttributes.addAll(Arrays.asList(configuredAttributes));
    } else {
        allowedAttributes.addAll(attributes.keySet());
    }
    if (excludedAttributes != null) {
        allowedAttributes.removeAll(Arrays.asList(excludedAttributes));
    }
    //Filter the attributes map
    for (final Iterator<String> attributeItr = attributes.keySet().iterator(); attributeItr.hasNext(); ) {
        final String attribute = attributeItr.next();
        if (!allowedAttributes.contains(attribute)) {
            attributeItr.remove();
            this.logger.warn("User '" + uid + "' attempted overriding attribute '" + attribute + "' which is not allowed in the current configuration. The attribute will be ignored.");
        }
    }
    this.logger.warn("User '" + uid + "' setting attribute overrides: " + attributes);
    //Override attributes retrieved the person directory
    this.overwritingPersonAttributeDao.setUserAttributeOverride(uid, attributes);
    //Update the IPerson, setting the overridden attributes
    final HttpServletRequest portalRequest = this.portalRequestUtils.getPortletHttpRequest(portletRequest);
    final IPerson person = this.personManager.getPerson(portalRequest);
    final Map<String, List<Object>> multivaluedAttributes = MultivaluedPersonAttributeUtils.toMultivaluedMap(attributes);
    person.setAttributes(multivaluedAttributes);
    person.setAttribute(OVERRIDDEN_ATTRIBUTES, multivaluedAttributes.keySet());
}
Also used : LinkedHashSet(java.util.LinkedHashSet) HashMap(java.util.HashMap) Attribute(org.apereo.portal.portlets.Attribute) HttpServletRequest(javax.servlet.http.HttpServletRequest) IPerson(org.apereo.portal.security.IPerson) Entry(java.util.Map.Entry) PortletRequest(javax.portlet.PortletRequest) IPersonAttributes(org.jasig.services.persondir.IPersonAttributes) PortletPreferences(javax.portlet.PortletPreferences) List(java.util.List) Principal(java.security.Principal)

Aggregations

IPersonAttributes (org.jasig.services.persondir.IPersonAttributes)33 List (java.util.List)12 IPerson (org.apereo.portal.security.IPerson)12 HashMap (java.util.HashMap)11 ArrayList (java.util.ArrayList)8 LinkedHashSet (java.util.LinkedHashSet)5 HttpServletRequest (javax.servlet.http.HttpServletRequest)5 Principal (java.security.Principal)4 Map (java.util.Map)4 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)4 PortletRequest (javax.portlet.PortletRequest)3 ModelAndView (org.springframework.web.servlet.ModelAndView)3 Date (java.util.Date)2 LinkedHashMap (java.util.LinkedHashMap)2 Set (java.util.Set)2 PortletPreferences (javax.portlet.PortletPreferences)2 Element (net.sf.ehcache.Element)2 GroupsException (org.apereo.portal.groups.GroupsException)2 IEntityGroup (org.apereo.portal.groups.IEntityGroup)2 Attribute (org.apereo.portal.portlets.Attribute)2