Search in sources :

Example 46 with IPerson

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

the class UserAttributeSkinMappingTransformerConfigurationSource method getSkinName.

@Override
protected String getSkinName(HttpServletRequest request) {
    final IUserInstance userInstance = this.userInstanceManager.getUserInstance(request);
    final IPerson person = userInstance.getPerson();
    final IPersonAttributes personAttrs = this.personAttributeDao.getPerson(person.getUserName());
    if (personAttrs == null) {
        logger.debug("No user attributes found for {} no skin override will be done", person.getUserName());
        return null;
    }
    final Object attributeValue = personAttrs.getAttributeValue(this.skinAttributeName);
    if (attributeValue == null) {
        logger.debug("No user {} does not have attribute {} defined, no skin override will be done", person.getUserName(), this.skinAttributeName);
        return null;
    }
    final String mappedSkinName = this.getMappedSkinName(attributeValue.toString());
    if (mappedSkinName == null) {
        logger.debug("No skin is mapped for attribute {}, no skin override will be done", attributeValue);
        return null;
    }
    logger.debug("Overidding skin to {}", mappedSkinName);
    return mappedSkinName;
}
Also used : IUserInstance(org.apereo.portal.user.IUserInstance) IPerson(org.apereo.portal.security.IPerson) IPersonAttributes(org.apereo.services.persondir.IPersonAttributes)

Example 47 with IPerson

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

the class RemoteUserPersonManager method getPerson.

/**
 * Retrieve an IPerson object for the incoming request
 *
 * @param request The current HttpServletRequest
 * @return IPerson object for the incoming request
 * @exception PortalSecurityException Description of the Exception
 */
@Override
public IPerson getPerson(HttpServletRequest request) throws PortalSecurityException {
    /*
         * This method overrides the implementation of getPerson() in BasePersonManager, but we only
         * want the RemoteUser behavior here if we're using RemoteUser AuthN.
         */
    if (!remoteUserSecurityContextFactory.isEnabled()) {
        return super.getPerson(request);
    }
    // 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 = createPersonForRequest(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;
        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();
                // 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
        logger.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 48 with IPerson

use of org.apereo.portal.security.IPerson 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, 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));
                }
            } 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());
            }
        }
        // Call extensions if present
        if (authenticationExt != null) {
            authenticationExt.postAttributeResolution(request, person);
        }
        // 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.
        final boolean autocreate = PropertiesManager.getPropertyAsBoolean("org.apereo.portal.services.Authentication.autoCreateUsers");
        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 49 with IPerson

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

the class UrlCanonicalizingFilter method doFilterInternal.

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    if ("GET".equals(request.getMethod())) {
        final String canonicalUrl = this.urlSyntaxProvider.getCanonicalUrl(request);
        final String canonicalUri;
        final int queryStringIndex = canonicalUrl.indexOf("?");
        if (queryStringIndex < 0) {
            canonicalUri = canonicalUrl;
        } else {
            canonicalUri = canonicalUrl.substring(0, queryStringIndex);
        }
        String requestURI = request.getRequestURI();
        // UP-4414.
        if (requestURI.contains(";jsessionid")) {
            requestURI = requestURI.substring(0, requestURI.indexOf(";"));
        }
        final int redirectCount = this.getRedirectCount(request);
        if (!canonicalUri.equals(requestURI)) {
            if (redirectCount < this.maximumRedirects) {
                this.setRedirectCount(request, response, redirectCount + 1);
                /*
                     * This is the place where we should decide if...
                     *   - (1) the user is a guest
                     *   - (2) the canonicalUrl is not the requested content
                     *   - (3) there is a strategy for external login
                     *
                     * If all of these are true, we should attempt to send the
                     * user to external login with a properly-encoded deep-linking
                     * service URL attached.
                     */
                String encodedTargetUrl = null;
                IPerson person = personManager.getPerson(request);
                if (/* #1 */
                person.isGuest() && /* #2 */
                urlSyntaxProvider.doesRequestPathReferToSpecificAndDifferentContentVsCanonicalPath(requestURI, canonicalUri) && /* #3 */
                loginRefUrlEncoder != null) {
                    encodedTargetUrl = loginRefUrlEncoder.encodeLoginAndRefUrl(request);
                }
                if (encodedTargetUrl == null) {
                    // For whatever reason, we haven't chosen to send the
                    // user through external login, so we use the canonicalUrl
                    encodedTargetUrl = response.encodeRedirectURL(canonicalUrl);
                }
                response.sendRedirect(encodedTargetUrl);
                logger.debug("Redirecting from {} to canonicalized URL {}, redirect {}", requestURI, canonicalUri, redirectCount);
                return;
            }
            this.clearRedirectCount(request, response);
            logger.debug("Not redirecting from {} to canonicalized URL {} due to limit of {} redirects", requestURI, canonicalUri, redirectCount);
        } else {
            logger.trace("Requested URI {} is the canonical URL {}, " + "so no (further?) redirect is necessary (after {} redirects).", requestURI, canonicalUri, redirectCount);
            if (redirectCount > 0) {
                this.clearRedirectCount(request, response);
            }
        }
    }
    final PortalHttpServletFactoryService.RequestAndResponseWrapper wrapper = servletFactoryService.createRequestAndResponseWrapper(request, response);
    filterChain.doFilter(wrapper.getRequest(), wrapper.getResponse());
}
Also used : IPerson(org.apereo.portal.security.IPerson)

Example 50 with IPerson

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

the class PortalHttpServletRequestWrapper method isUserInRole.

/**
 * Determines whether or not the user is in the given role. The wrapped request is consulted
 * first then the {@link GroupService} is used to determine if a group exists for the specified
 * role and if the user is a member of it.
 *
 * <p>Role is case sensitive.
 *
 * @see
 *     org.apereo.portal.utils.web.AbstractHttpServletRequestWrapper#isUserInRole(java.lang.String)
 */
@Override
public boolean isUserInRole(String role) {
    if (super.getSession(false) == null) {
        return super.isUserInRole(role);
    }
    // Check the wrapped request first
    final boolean isUserInRole = super.isUserInRole(role);
    if (isUserInRole) {
        return true;
    }
    // Find the group for the role, if not found return false
    IEntityGroup groupForRole = GroupService.findGroup(role);
    if (groupForRole == null) {
        final EntityIdentifier[] results = GroupService.searchForGroups(role, GroupService.SearchMethod.DISCRETE, IPerson.class);
        if (results == null || results.length == 0) {
            return false;
        }
        if (results.length > 1) {
            this.logger.warn(results.length + " groups were found for role '" + role + "'. The first result will be used.");
        }
        IGroupMember member = GroupService.getGroupMember(results[0]);
        if (member == null || !member.isGroup()) {
            return false;
        }
        groupForRole = member.asGroup();
    }
    // Load the group information about the current user
    final IUserInstance userInstance = this.userInstanceManager.getUserInstance(this.getWrappedRequest());
    final IPerson person = userInstance.getPerson();
    final EntityIdentifier personEntityId = person.getEntityIdentifier();
    final IGroupMember personGroupMember = GroupService.getGroupMember(personEntityId);
    final boolean rslt = personGroupMember.isDeepMemberOf(groupForRole);
    logger.trace("Answering {} for isUserInRole where user='{}', role='{}', and groupForRole='{}'", rslt, person.getUserName(), role, groupForRole.getName());
    return rslt;
}
Also used : IEntityGroup(org.apereo.portal.groups.IEntityGroup) IUserInstance(org.apereo.portal.user.IUserInstance) IGroupMember(org.apereo.portal.groups.IGroupMember) IPerson(org.apereo.portal.security.IPerson) EntityIdentifier(org.apereo.portal.EntityIdentifier)

Aggregations

IPerson (org.apereo.portal.security.IPerson)198 Test (org.junit.Test)52 PersonImpl (org.apereo.portal.security.provider.PersonImpl)45 ModelAndView (org.springframework.web.servlet.ModelAndView)43 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)34 HttpServletRequest (javax.servlet.http.HttpServletRequest)32 IUserInstance (org.apereo.portal.user.IUserInstance)27 HashMap (java.util.HashMap)25 HttpSession (javax.servlet.http.HttpSession)22 IAuthorizationPrincipal (org.apereo.portal.security.IAuthorizationPrincipal)22 ArrayList (java.util.ArrayList)20 EntityIdentifier (org.apereo.portal.EntityIdentifier)18 ISecurityContext (org.apereo.portal.security.ISecurityContext)17 IPersonAttributes (org.apereo.services.persondir.IPersonAttributes)17 IPortletDefinition (org.apereo.portal.portlet.om.IPortletDefinition)15 List (java.util.List)14 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)12 Map (java.util.Map)11 Set (java.util.Set)11 IUserProfile (org.apereo.portal.IUserProfile)11