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);
}
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;
}
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;
}
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);
}
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());
}
Aggregations