Example usage for javax.security.auth Subject getPrincipals

List of usage examples for javax.security.auth Subject getPrincipals

Introduction

In this page you can find the example usage for javax.security.auth Subject getPrincipals.

Prototype

public <T extends Principal> Set<T> getPrincipals(Class<T> c) 

Source Link

Document

Return a Set of Principals associated with this Subject that are instances or subclasses of the specified Class .

Usage

From source file:org.josso.gateway.identity.service.SSOIdentityProviderImpl.java

/**
 * This method logins a user into de SSO infrastructure.
 *
 * @param cred   the user credentials used as user identity proof.
 * @param scheme the authentication scheme name to be used for logging in the user.
 * @throws AuthenticationFailureException if authentication fails.
 * @throws SSOException                   if an error occurs.
 *//*from  w  w  w.j  a va 2 s . co m*/
public SSOSession login(Credential[] cred, String scheme) throws SSOException, SSOAuthenticationException {

    SSOContext ctx = SSOContext.getCurrent();

    try {

        SecurityDomain domain = Lookup.getInstance().lookupSecurityDomain();

        // Configure this ...!
        SSOIdentityManager im = domain.getIdentityManager();
        SSOSessionManager sm = domain.getSessionManager();
        Authenticator au = domain.getAuthenticator();

        // 1. Invalidate current session
        SSOSession currentSession = ctx.getSession();
        if (currentSession != null) {
            try {
                if (logger.isDebugEnabled())
                    logger.debug("Invalidating existing session : " + currentSession.getId());
                sm.invalidate(currentSession.getId());
            } catch (Exception e) {
                logger.warn(
                        "Can't ivalidate current session : " + currentSession.getId() + "\n" + e.getMessage(),
                        e);
            }
        }

        // 2. Authenticate using credentials :
        Subject s = au.check(cred, scheme);
        Set principals = s.getPrincipals(SimplePrincipal.class);
        if (principals.size() != 1) {
            // The Set should NEVER be empty or have more than one Principal ...
            // In the future, we could have more than one principal if authenticated with multiple schemes.
            throw new SSOException("Assertion failed : principals.size() != 1");
        }

        // 3. Find SSO User, authentication was successfull and we have only one principal
        // Check the username with the IdentityManager, just to be sure it's a valid user:
        Principal p = (Principal) principals.iterator().next();
        im.userExists(p.getName());

        // 4. Create a new sso session :
        String ssoSessionId = sm.initiateSession(p.getName(), s);
        SSOSession session = sm.getSession(ssoSessionId);

        notifyLoginSuccess(session.getUsername(), session, scheme);

        return session;

    } catch (AuthenticationFailureException e) {
        if (logger.isDebugEnabled())
            logger.debug(e.getMessage(), e);
        // Re-throw current exception ...
        notifyLoginFailed(cred, scheme, e);
        throw e;

    } catch (SSOAuthenticationException e) {
        if (logger.isDebugEnabled())
            logger.debug(e.getMessage(), e);
        // Re-throw current exception ...
        notifyLoginFailed(cred, scheme, e);
        throw e;

    } catch (SSOIdentityException e) {
        if (logger.isDebugEnabled())
            logger.debug(e.getMessage(), e);
        notifyLoginFailed(cred, scheme, e);
        throw new SSOException(e.getMessage(), e);

    } catch (SSOSessionException e) {
        if (logger.isDebugEnabled())
            logger.debug(e.getMessage(), e);
        notifyLoginFailed(cred, scheme, e);
        throw new SSOException(e.getMessage(), e);
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        notifyLoginFailed(cred, scheme, e);
        throw new SSOException(e.getMessage(), e);

    }
}

From source file:org.betaconceptframework.astroboa.engine.jcr.util.PopulateContentObject.java

private RepositoryUser retrieveRepositoryUserForActiveClient() throws RepositoryException {

    SecurityContext securityContext = AstroboaClientContextHolder.getActiveSecurityContext();

    String repositoryUserId = null;
    String activeUsername = null;

    if (securityContext != null) {

        Subject subject = securityContext.getSubject();

        if (subject != null
                && CollectionUtils.isNotEmpty(subject.getPrincipals(RepositoryUserIdPrincipal.class))) {

            repositoryUserId = subject.getPrincipals(RepositoryUserIdPrincipal.class).iterator().next()
                    .getName();/*from  www .  j a va  2s.  c  om*/

            Node repositoryUserNode = context.retrieveNodeForRepositoryUser(repositoryUserId);

            return repositoryUserDao.renderRepositoryUserFromNode(repositoryUserNode, session, null, null);
        } else {
            //Could not locate repository user id. Try with user name
            activeUsername = securityContext.getIdentity();

            return repositoryUserDao.getRepositoryUser(activeUsername);

        }
    }

    throw new CmsException("Could not locate a RepositoryUser neither with  identifier " + repositoryUserId
            + " nor with externalId " + activeUsername);

}

From source file:com.buaa.cfs.security.UserGroupInformation.java

/**
 * Return the current user, including any doAs in the current stack.
 *
 * @return the current user//from   ww w.j  av a2s . c om
 *
 * @throws IOException if login fails
 */

public synchronized static UserGroupInformation getCurrentUser() throws IOException {
    AccessControlContext context = AccessController.getContext();
    Subject subject = Subject.getSubject(context);
    if (subject == null || subject.getPrincipals(User.class).isEmpty()) {
        return getLoginUser();
    } else {
        return new UserGroupInformation(subject);
    }
}

From source file:com.buaa.cfs.security.UserGroupInformation.java

/**
 * Create a UserGroupInformation from a Subject with Kerberos principal.
 *
 * @throws IOException if the kerberos login fails
 *///from   www.j ava  2s  . c  om
public static UserGroupInformation getUGIFromSubject(Subject subject) throws IOException {
    if (subject == null) {
        throw new IOException("Subject must not be null");
    }

    if (subject.getPrincipals(KerberosPrincipal.class).isEmpty()) {
        throw new IOException("Provided Subject must contain a KerberosPrincipal");
    }

    KerberosPrincipal principal = subject.getPrincipals(KerberosPrincipal.class).iterator().next();

    User ugiUser = new User(principal.getName(), AuthenticationMethod.KERBEROS, null);
    subject.getPrincipals().add(ugiUser);
    UserGroupInformation ugi = new UserGroupInformation(subject);
    ugi.setLogin(null);
    ugi.setAuthenticationMethod(AuthenticationMethod.KERBEROS);
    return ugi;
}

From source file:org.betaconceptframework.astroboa.engine.service.security.aspect.SecureContentServiceAspect.java

private void addSecurityCriteriaToContentObjectCriteria(ContentObjectCriteria localCopyOfContentObjectCriteria,
        String userId, List<String> prefixedRoles, SecurityContext activeSecurityContext) {

    // if the authenticated user has not been granted the role: ROLE_CMS_INTERNAL_VIEWER 
    // then we allow her to read only published content objects i.e. those that their status is equal to "published" or "publishedAndArchived".
    // As of today a published content object overrules any "read" security option to prevent complexities in security rule handling 
    // and remove the extra effort required for the publisher of content objects 
    // It is not very convenient to require to change the "read" security option of published content objects to "ALL" to allow to be read by REPOSITORY 
    // and then when publication status ends revert back to previous security settings. 
    // Additionally "ALL" should be interpreted as "REPOSITORY PHYSICAL PERSONS or REPOSITORY USERS WHICH ARE EXPLICITLY GRANTED THE PERMISSION TO VIEW THE REPOSITORY, 
    // i.e. those in role ROLE_CMS_INTERNAL_VIEWER".
    // Anonymous is not an actual user registered in the identity store. It is a convention introduced in order to cope with the security rule that we always need some user 
    // in order to permit access to content. So for any user that tries to see the repository without logging in, the front-end system, e.g. the web application, should
    // silently perform a virtual login as the anonymous user.
    ///*from  w  w w  .jav  a  2 s.c  om*/
    // Through the above convention it becomes really easy to publish and un-publish content objects. 
    // The idea is that if someone publishes a content object then she implicitly removes any read restrictions.
    // All other restrictions apply and furthermore read restrictions are still there and remain valid when status is not set to "published" any more.
    // We may revisit this convention if the use of the repository reveals another way of interpreting anonymous requests and published objects
    //
    // Be aware that since the anonymous is a virtual user it is not granted any roles. So allowing users that are not granted the role:ROLE_CMS_INTERNAL_VIEWER 
    // to view only published content objects is sufficient and we do not actually need to check whether the user is the anonymous.

    // However we explicitly check if the user identity is the anonymous in order to prevent cases where some administrator by mistake or on purpose 
    // registers the anonymous as a real user and assigns it the role ROLE_CMS_INTERNAL_VIEWER. 
    // This would result in letting all not logged in Internet users to view internal unpublished content. So we introduce the extra rule that 
    // anonymous is only viewing published objects despite any roles that may have been assigned to it.

    //if (StringUtils.equals(userId, IdentityPrincipal.ANONYMOUS) ||
    if (!activeSecurityContext.hasRole(CmsRoleAffiliationFactory.INSTANCE
            .getCmsRoleAffiliationForActiveRepository(CmsRole.ROLE_CMS_INTERNAL_VIEWER))) {

        //The anonymous user or any other user that is NOT GRANTED the role:ROLE_CMS_INTERNAL_VIEWER can access ONLY PUBLISHED content objects
        //In case where criteria already contains criterion that requires content object status to equal "publishedAndArchived", 
        // there is no need to add criterion about published
        Criterion contentObjectIsPublishedCriterion = null;
        if (!criteriaContainsContentObjectStatusArchivedCriterion(
                localCopyOfContentObjectCriteria.getCriteria())) {
            contentObjectIsPublishedCriterion = CriterionFactory.equals("profile.contentObjectStatus",
                    ContentObjectStatus.published.toString());
            localCopyOfContentObjectCriteria.addCriterion(contentObjectIsPublishedCriterion);
        }

        //TODO: we should check whether user has already include a criterion concerning content object status and prohibit the query execution if a status other than published has been requested
        // additionally if there s already a criterion asking for published content objects we should keep it only once and not add it again

        // generate a warning that only published content objects have been returned
        //logger.warn("The authenticated user is the 'anonymous' user. Be aware that the queries issued by anonymous user return only published content objects");
    } else if (!AbstractSecureContentObjectAspect.userHasRole(activeSecurityContext,
            CmsRoleAffiliationFactory.INSTANCE.getCmsRoleAffiliationForActiveRepository(CmsRole.ROLE_ADMIN))) { // for USER with role ROLE_ADMIN we do not impose any security constraint
        // we will generate criteria to generate the following security restriction
        // (@betaconcept:OwnerCmsIdentifier = UUIDOfUserExecutingTheQuery OR
        // betaconcept:CanBeReadBy = 'REPOSITORY' OR (betaconcept:CanBeReadBy != 'NONE'
        // AND (betaconcept:CanBeReadBy = "USR_" + userId OR
        // betaconcept:CanBeReadBy = "GRP_" + userGroupId1 OR
        // betaconcept:CanBeReadBy = "GRP_" + userGroupId2 ....)))

        Criterion ownerCriterion = null;
        RepositoryUserIdPrincipal ownerIdPrincipal = null;

        Subject subject = activeSecurityContext.getSubject();

        if (subject != null
                && CollectionUtils.isNotEmpty(subject.getPrincipals(RepositoryUserIdPrincipal.class))) {
            ownerIdPrincipal = subject.getPrincipals(RepositoryUserIdPrincipal.class).iterator().next();
            ownerCriterion = CriterionFactory.equals("owner", ownerIdPrincipal.getName());
        }

        Criterion canBeReadByAllCriterion = CriterionFactory.equals("accessibility.canBeReadBy",
                ContentAccessMode.ALL.toString());
        Criterion canBeReadByNotEQNoneCriterion = CriterionFactory.notEquals("accessibility.canBeReadBy",
                ContentAccessMode.NONE.toString());

        // we check whether read access is permitted either to any of the user groups or explicitly to the user itself
        // so we add the user id into the list of group ids. All ids are appropriately prefixed by either URS_ or GRP_ to
        // distinguish between user and group ids
        prefixedRoles.add(userId);

        Criterion canBeReadByUserHerselfOrUserGroupsCriterion = CriterionFactory
                .equals("accessibility.canBeReadBy", Condition.OR, prefixedRoles);
        // build query parts
        Criterion firstPart = null;
        if (ownerCriterion != null) {
            firstPart = CriterionFactory.or(ownerCriterion, canBeReadByAllCriterion);
        } else {
            firstPart = canBeReadByAllCriterion;
        }

        Criterion secondPart = CriterionFactory.and(canBeReadByNotEQNoneCriterion,
                canBeReadByUserHerselfOrUserGroupsCriterion);

        // connect the parts
        Criterion securityCriterion = CriterionFactory.or(firstPart, secondPart);

        // add the security criteria to user provided search criteria
        localCopyOfContentObjectCriteria.addCriterion(securityCriterion);

    }
}

From source file:org.josso.jb4.agent.JBossCatalinaRealm.java

/**
 * Return the Principal associated with the specified username and
 * credentials, if there is one; otherwise return null.
 *
 * The method was completely rewritten since the overriden operation,
 * on succesfull authentication, sets as the authenticated Principal
 * a SimplePrincipal instantiated using the provided username.
 * The problem is that in JOSSO the username is a SSO Session Id, not
 * a username. So we need to set the SSOUser returned by the JAAS Gateway
 * Login Module as the authenticatd Principal.
 * Since the JaasSecurityManager caches the authenticated user using the
 * Principal referring to a JOSSO Session Id, we will need to map, for
 * example when roles are checked against the realm, a user Principal
 * back to its JOSSO Session Identifier Principal. This way the the user
 * and its roles can be retrieved correctly by the JaasSecurityManager.
 *
 * @param username Username of the Principal to look up
 * @param credentials Password or other credentials to use in
 * authenticating this username//from  w  w  w  . j a  v a2s .c  om
 */
public Principal authenticate(String username, String credentials) {

    logger.debug("Begin authenticate, username=" + username);

    Principal principal = null;
    SSOUser ssoUser = null;
    Principal caller = (Principal) SecurityAssociationValve.userPrincipal.get();
    if (caller == null && username == null && credentials == null)
        return null;

    try {
        Context securityCtx = null;
        securityCtx = prepareENC();

        if (securityCtx == null) {
            logger.error("No security context for authenticate(String, String)");
            return null;
        }

        // Get the JBoss security manager from the ENC context
        SubjectSecurityManager securityMgr = (SubjectSecurityManager) securityCtx.lookup("securityMgr");
        if (!isSSODomain(securityMgr.getSecurityDomain())) {
            // This is not a SSO Security domain, let JBoss realm handle this ...
            return super.authenticate(username, credentials);
        }

        principal = new SimplePrincipal(username);
        char[] passwordChars = null;
        if (credentials != null)
            passwordChars = credentials.toCharArray();
        Subject subject = new Subject();
        if (securityMgr.isValid(principal, credentials, subject)) {
            logger.debug("User: " + username + " is authenticated");

            // Get the authorized subject set by the isValid() call on succesful
            // authentication.
            //Subject activeSubject = securityMgr.getActiveSubject();

            logger.debug("Authenticated Subject: " + subject);

            Set principals = subject.getPrincipals(SSOUser.class);
            Iterator i = principals.iterator();
            while (i.hasNext()) {
                ssoUser = (SSOUser) i.next();
                break;
            }

            // Make the cache aware of the user-session association so that
            // it can handle correctly cache entry lookups.
            //_cachePolicy.attachSessionToUser(principal, ssoUser);

            // Instead of associating the Principal used for authenticating (which is a
            // session id), sets the authenticated principal to the SSOUser part of the
            // Subject returned by the Gateway.
            JBossSecurityAssociationActions.setPrincipalInfo(ssoUser, passwordChars, subject);

            // Get the CallerPrincipal mapping
            RealmMapping rm = (RealmMapping) securityCtx.lookup("realmMapping");
            Principal oldPrincipal = ssoUser;
            principal = rm.getPrincipal(oldPrincipal);
            logger.debug("Mapped from input principal: " + oldPrincipal + " to: " + principal);

            // Get the caching principal
            principal = getCachingPrincpal(rm, oldPrincipal, principal, credentials, subject);

        } else {
            principal = null;
            logger.debug("User: " + username + " is NOT authenticated");
        }
    } catch (NamingException e) {
        principal = null;
        logger.error("Error during authenticate", e);
    }
    logger.debug("End authenticate, principal=" + ssoUser);
    return ssoUser;
}

From source file:com.dtolabs.rundeck.core.authorization.RuleEvaluator.java

private AclSubject subjectFrom(final Subject subject) {
    if (null == subject) {
        throw new NullPointerException("subject is null");
    }//w w w .  ja  v  a 2 s.  com
    Set<Username> userPrincipals = subject.getPrincipals(Username.class);
    final String username;
    if (userPrincipals.size() > 0) {
        Username usernamep = userPrincipals.iterator().next();
        username = usernamep.getName();
    } else {
        username = null;
    }
    Set<Group> groupPrincipals = subject.getPrincipals(Group.class);
    final Set<String> groupNames = new HashSet<>();
    if (groupPrincipals.size() > 0) {
        for (Group groupPrincipal : groupPrincipals) {
            groupNames.add(groupPrincipal.getName());
        }
    }
    return new AclSubject() {
        @Override
        public String getUsername() {
            return username;
        }

        @Override
        public Set<String> getGroups() {
            return groupNames;
        }
    };
}

From source file:org.betaconceptframework.astroboa.engine.service.security.aspect.SecureContentServiceAspect.java

private Object grantOrDenyAccessToContentObject(ProceedingJoinPoint proceedingJoinPoint,
        String contentObjectIdOrSystemName, Object[] methodParameters,
        ResourceRepresentationType contentObjectOutput) {
    if (contentObjectIdIsNotNull(contentObjectIdOrSystemName)) {
        SecurityContext activeSecurityContext = AbstractSecureContentObjectAspect.retrieveSecurityContext();

        //Retrieve jcr node which corresponds to requested content object
        Node contentObjectNode = null;

        try {// w  ww .j  a  v  a  2  s.c o  m

            if (!(proceedingJoinPoint.getTarget() instanceof ContentServiceImpl)) {
                return generateEmptyOutcome(contentObjectOutput);
            }

            contentObjectNode = ((ContentServiceImpl) proceedingJoinPoint.getTarget())
                    .getContentObjectNodeByIdOrSystemName(contentObjectIdOrSystemName);

            //contentObject = (ContentObject) proceedingJoinPoint.proceed(methodParameters);

            if (contentObjectNode == null) {
                return generateEmptyOutcome(contentObjectOutput);
            }

            String userId = activeSecurityContext.getIdentity();

            // if the authenticated user has not been granted the role: ROLE_CMS_INTERNAL_VIEWER 
            // then we allow her to read only published content objects i.e. those that their status is equal to "published" or "publishedAndArchived".
            // As of today a published content object overrules any "read" security option to prevent complexities in security rule handling 
            // and remove the extra effort required for the publisher of content objects 
            // It is not very convenient to require to change the "read" security option of published content objects to "ALL" to allow to be read by REPOSITORY 
            // and then when publication status ends revert back to previous security settings. 
            // Additionally "ALL" should be interpreted as "REPOSITORY PHYSICAL PERSONS or REPOSITORY USERS WHICH ARE EXPLICITLY GRANTED THE PERMISSION TO VIEW THE REPOSITORY, 
            // i.e. those in role ROLE_CMS_INTERNAL_VIEWER".
            // Anonymous is not an actual user registered in the identity store. It is a convention introduced in order to cope with the security rule that we always need some user 
            // in order to permit access to content. So for any user that tries to see the repository without logging in, the front-end system, e.g. the web application, should
            // silently perform a virtual login as the anonymous user.
            //
            // Through the above convention it becomes really easy to publish and un-publish content objects. 
            // The idea is that if someone publishes a content object then she implicitly removes any read restrictions.
            // All other restrictions apply and furthermore read restrictions are still there and remain valid when status is not set to "published" any more.
            // We may revisit this convention if the use of the repository reveals another way of interpreting anonymous requests and published objects
            //
            // Be aware that since the anonymous is a virtual user it is not granted any roles. So allowing users that are not granted the role:ROLE_CMS_INTERNAL_VIEWER 
            // to view only published content objects is sufficient and we do not actually need to check whether the user is the anonymous.

            // However we explicitly check if the user identity is the anonymous in order to prevent cases where some administrator by mistake or on purpose 
            // registers the anonymous as a real user and assigns it the role ROLE_CMS_INTERNAL_VIEWER. 
            // This would result in letting all not logged in Internet users to view internal unpublished content. So we introduce the extra rule that 
            // anonymous is only viewing published objects despite any roles that may have been assigned to it.

            //if (StringUtils.equals(userId, IdentityPrincipal.ANONYMOUS) ||
            if (!AbstractSecureContentObjectAspect.userHasRole(activeSecurityContext,
                    CmsRoleAffiliationFactory.INSTANCE
                            .getCmsRoleAffiliationForActiveRepository(CmsRole.ROLE_CMS_INTERNAL_VIEWER))) {

                //Any user that is NOT GRANTED the role:ROLE_CMS_INTERNAL_VIEWER can access ONLY PUBLISHED or PublishedAndArchived content objects
                //StringProperty profileContentObjectStatusProperty = (StringProperty)contentObject.getCmsProperty("profile.contentObjectStatus");

                //if (profileContentObjectStatusProperty == null || profileContentObjectStatusProperty.hasNoValues()){
                if (!contentObjectNode.hasProperty("profile/contentObjectStatus")) {
                    logger.debug(
                            "User {} has not been granted access to content object {} because she has not been granted role ROLE_CMS_INTERNAL_VIEWER and "
                                    + " content object status is either null or has no values",
                            userId, contentObjectIdOrSystemName);
                    return generateEmptyOutcome(contentObjectOutput);
                }

                //String profileContentObjectStatus = profileContentObjectStatusProperty.getSimpleTypeValue();
                String profileContentObjectStatus = contentObjectNode.getProperty("profile/contentObjectStatus")
                        .getString();

                if (StringUtils.equals(ContentObjectStatus.published.toString(), profileContentObjectStatus)
                        || StringUtils.equals(ContentObjectStatus.publishedAndArchived.toString(),
                                profileContentObjectStatus)) {
                    logger.debug(
                            "User {} has been granted access to content object {} because she has not been granted role ROLE_CMS_INTERNAL_VIEWER but "
                                    + " content object status is {}",
                            new Object[] { userId, contentObjectIdOrSystemName, profileContentObjectStatus });

                    //
                    if (!CmsConstants.UUIDPattern.matcher(contentObjectIdOrSystemName).matches()
                            && methodParameters != null && methodParameters.length > 1
                            && contentObjectNode.hasProperty(CmsBuiltInItem.CmsIdentifier.getJcrName())) {
                        //User has provided object system name. replace it with object identifier
                        methodParameters[0] = contentObjectNode
                                .getProperty(CmsBuiltInItem.CmsIdentifier.getJcrName()).getString();
                    }

                    return proceedingJoinPoint.proceed(methodParameters);
                }

                logger.debug(
                        "User {} has not been granted access to content object {} because she has not been granted role ROLE_CMS_INTERNAL_VIEWER and "
                                + " content object status '{}' is not published or published and archived",
                        new Object[] { userId, contentObjectIdOrSystemName, profileContentObjectStatus });

                return generateEmptyOutcome(contentObjectOutput);

            } else if (!AbstractSecureContentObjectAspect.userHasRole(activeSecurityContext,
                    CmsRoleAffiliationFactory.INSTANCE
                            .getCmsRoleAffiliationForActiveRepository(CmsRole.ROLE_ADMIN))) { // for USER with ROLE_ADMIN we do not impose any security constraint

                // we will generate criteria to generate the following security restriction
                // (@betaconcept:OwnerCmsIdentifier = UUIDOfUserExecutingTheQuery OR
                // betaconcept:CanBeReadBy = 'REPOSITORY' OR (betaconcept:CanBeReadBy != 'NONE'
                // AND (betaconcept:CanBeReadBy = "USR_" + userId OR
                // betaconcept:CanBeReadBy = "GRP_" + userGroupId1 OR
                // betaconcept:CanBeReadBy = "GRP_" + userGroupId2 ....)))

                //User has role ROLE_CMS_INTERNAL_VIEWER

                //Check if user owns this content object
                //RepositoryUser owner = contentObject.getOwner();

                Subject subject = activeSecurityContext.getSubject();

                if (subject != null
                        && CollectionUtils.isNotEmpty(subject.getPrincipals(RepositoryUserIdPrincipal.class))
                        && contentObjectNode.hasProperty(CmsBuiltInItem.OwnerCmsIdentifier.getJcrName())) {
                    RepositoryUserIdPrincipal ownerIdPrincipal = subject
                            .getPrincipals(RepositoryUserIdPrincipal.class).iterator().next();

                    String ownerId = contentObjectNode
                            .getProperty(CmsBuiltInItem.OwnerCmsIdentifier.getJcrName()).getString();

                    if (StringUtils.equals(ownerId, ownerIdPrincipal.getName())) {
                        logger.debug(
                                "User {} has been granted access to content object {} because she owns the content object",
                                userId, contentObjectIdOrSystemName);

                        if (!CmsConstants.UUIDPattern.matcher(contentObjectIdOrSystemName).matches()
                                && methodParameters != null && methodParameters.length > 1
                                && contentObjectNode.hasProperty(CmsBuiltInItem.CmsIdentifier.getJcrName())) {
                            //User has provided object system name. replace it with object identifier
                            methodParameters[0] = contentObjectNode
                                    .getProperty(CmsBuiltInItem.CmsIdentifier.getJcrName()).getString();
                        }

                        return proceedingJoinPoint.proceed(methodParameters);
                    }
                }

                //TODO : In case RepositoryUserIdPrincipal is not available, is it safe to just do the following check
                //  owner.getExternalId() == userId

                //User does not own content object. Check access right defined in property
                //accessibility.canBeReadBy
                //StringProperty accessibilityCanBeReadByProperty = (StringProperty) contentObject.getCmsProperty("accessibility.canBeReadBy");

                //if (accessibilityCanBeReadByProperty == null || accessibilityCanBeReadByProperty.hasNoValues()){
                if (!contentObjectNode.hasProperty("accessibility/canBeReadBy")) {
                    logger.debug(
                            "User {} has not been granted access to content object {} because although she does not own content objects and  "
                                    + " content object does not have any value to property accessibility.canBeReadBy ",
                            userId, contentObjectIdOrSystemName);
                    return generateEmptyOutcome(contentObjectOutput);
                }

                //List<String> canBeReadBy = accessibilityCanBeReadByProperty.getSimpleTypeValues();
                Value[] canBeReadByArr = contentObjectNode.getProperty("accessibility/canBeReadBy").getValues();

                List<String> canBeReadBy = new ArrayList<String>();
                for (Value value : canBeReadByArr) {
                    canBeReadBy.add(value.getString());
                }

                //If canBeReadBy contains REPOSITORY value then access is granted
                if (canBeReadBy.contains(ContentAccessMode.ALL.toString())) {
                    logger.debug(
                            "User {} has been granted access to content object {} because although she does not own content object, "
                                    + " content object property accessibility.canBeReadBy contains value REPOSITORY :{}",
                            new Object[] { userId, contentObjectIdOrSystemName, canBeReadBy.toString() });

                    if (!CmsConstants.UUIDPattern.matcher(contentObjectIdOrSystemName).matches()
                            && methodParameters != null && methodParameters.length > 1
                            && contentObjectNode.hasProperty(CmsBuiltInItem.CmsIdentifier.getJcrName())) {
                        //User has provided object system name. replace it with object identifier
                        methodParameters[0] = contentObjectNode
                                .getProperty(CmsBuiltInItem.CmsIdentifier.getJcrName()).getString();
                    }

                    return proceedingJoinPoint.proceed(methodParameters);
                }

                //If canBeReadBy contains NONE value then access is denied
                if (canBeReadBy.contains(ContentAccessMode.NONE.toString())) {
                    logger.debug(
                            "User {} has not been granted access to content object {} because she does not own content object and  "
                                    + " content object property accessibility.canBeReadBy contains value NONE :{}",
                            new Object[] { userId, contentObjectIdOrSystemName, canBeReadBy.toString() });
                    return generateEmptyOutcome(contentObjectOutput);
                }

                //canBeReadBy contains neither REPOSITORY nor NONE
                //access is granted only if either to any of the user groups or explicitly to the user itself
                // so we add the user id into the list of group ids. All ids are appropriately prefixed by either URS_ or GRP_ to
                // distinguish between user and group ids

                // Security in each content object is defined by four lists stored as part of each object (i.e. a special complex property of each content object).
                //    The four lists define which user or role (role may be a role group also) can respectively read, update, delete and tag the object.
                //    Each of the four lists inside each object contain a mixed set of the userIds and Roles  which 
                // So we get the user roles prefixed by "GRP_" in order to discriminate them from user ids which are prefixed with "USR_"
                List<String> prefixedRoles = activeSecurityContext.getAllRoles();

                prefixedRoles.add(userId);

                for (String prefixedRole : prefixedRoles) {
                    if (canBeReadBy.contains(prefixedRole)) {
                        logger.debug(
                                "User {} has been granted access to content object {} because although she does not own content object,   "
                                        + " content object property accessibility.canBeReadBy contains role {} ",
                                new Object[] { userId, contentObjectIdOrSystemName, prefixedRole });

                        if (!CmsConstants.UUIDPattern.matcher(contentObjectIdOrSystemName).matches()
                                && methodParameters != null && methodParameters.length > 1
                                && contentObjectNode.hasProperty(CmsBuiltInItem.CmsIdentifier.getJcrName())) {
                            //User has provided object system name. replace it with object identifier
                            methodParameters[0] = contentObjectNode
                                    .getProperty(CmsBuiltInItem.CmsIdentifier.getJcrName()).getString();
                        }

                        return proceedingJoinPoint.proceed(methodParameters);
                    }
                }

                logger.debug(
                        "User {} has not been granted access to content object {} because she does not own content object and  "
                                + " content object property accessibility.canBeReadBy does not contain any role which has been assigned to user. \nAccessibility.CanBeReadBy values {}"
                                + "\n Granted Roles to user {}",
                        new Object[] { userId, contentObjectIdOrSystemName, canBeReadBy, prefixedRoles });
                return generateEmptyOutcome(contentObjectOutput);
            } else {
                logger.debug(
                        "User {} has been granted access to content object {} because she has been granted role ROLE_ADMIN ",
                        new Object[] { userId, contentObjectIdOrSystemName });

                if (!CmsConstants.UUIDPattern.matcher(contentObjectIdOrSystemName).matches()
                        && methodParameters != null && methodParameters.length > 1
                        && contentObjectNode.hasProperty(CmsBuiltInItem.CmsIdentifier.getJcrName())) {
                    //User has provided object system name. replace it with object identifier
                    methodParameters[0] = contentObjectNode
                            .getProperty(CmsBuiltInItem.CmsIdentifier.getJcrName()).getString();
                }

                return proceedingJoinPoint.proceed(methodParameters);
            }
        } catch (CmsException e) {
            throw e;
        } catch (Throwable e) {
            throw new CmsException(e);
        }
    } else {
        //No point to proceed to actual method since no content object id is provided
        logger.debug("No content object exists with id {} therefore no restrictions are imposed",
                contentObjectIdOrSystemName);
        return generateEmptyOutcome(contentObjectOutput);
    }

}

From source file:org.betaconceptframework.astroboa.engine.jcr.dao.RepositoryDao.java

private String retrieveIdentityFromSubject(Subject subject) {

    if (subject == null || CollectionUtils.isEmpty(subject.getPrincipals(IdentityPrincipal.class))) {
        throw new CmsException("Could not find identity principal in subject " + subject
                + " Unable to create authentication token");
    }//from w  w  w .  jav a 2s . co  m

    //Retrieve the first one. Normally it should not have more than one
    return subject.getPrincipals(IdentityPrincipal.class).iterator().next().getName();
}

From source file:org.josso.jb32.agent.JBossCatalinaRealm.java

/**
 * Return the Principal associated with the specified username and
 * credentials, if there is one; otherwise return null.
 *
 * The method was completely rewritten since the overriden operation,
 * on succesfull authentication, sets as the authenticated Principal
 * a SimplePrincipal instantiated using the provided username.
 * The problem is that in JOSSO the username is a SSO Session Id, not
 * a username. So we need to set the SSOUser returned by the JAAS Gateway
 * Login Module as the authenticatd Principal.
 * Since the JaasSecurityManager caches the authenticated user using the
 * Principal referring to a JOSSO Session Id, we will need to map, for
 * example when roles are checked against the realm, a user Principal
 * back to its JOSSO Session Identifier Principal. This way the the user
 * and its roles can be retrieved correctly by the JaasSecurityManager.
 *
 * @param username Username of the Principal to look up
 * @param credentials Password or other credentials to use in
 * authenticating this username//from  w ww . j  a va2  s . c  o m
 */
public Principal authenticate(String username, String credentials) {

    logger.debug("Begin authenticate, username=" + username);

    Principal principal = null;
    SSOUser ssoUser = null;
    Principal caller = (Principal) SecurityAssociationValve.userPrincipal.get();
    if (caller == null && username == null && credentials == null)
        return null;

    try {
        Context securityCtx = null;
        securityCtx = prepareENC();

        if (securityCtx == null) {
            logger.error("No security context for authenticate(String, String)");
            return null;
        }

        // Get the JBoss security manager from the ENC context
        SubjectSecurityManager securityMgr = (SubjectSecurityManager) securityCtx.lookup("securityMgr");
        if (!isSSODomain(securityMgr.getSecurityDomain())) {
            // This is not a SSO Security domain, let JBoss realm handle this ...
            return super.authenticate(username, credentials);
        }

        principal = new SimplePrincipal(username);
        char[] passwordChars = null;
        if (credentials != null)
            passwordChars = credentials.toCharArray();

        Subject subject = new Subject();
        if (securityMgr.isValid(principal, passwordChars, subject)) {
            logger.debug("User: " + username + " is authenticated");

            // Get the authorized subject set by the isValid() call on succesful
            // authentication.
            // Subject activeSubject = securityMgr.getActiveSubject();

            // logger.debug("Authenticated Subject: " + activeSubject);

            logger.debug("Authenticated Subject: " + subject);

            Set principals = subject.getPrincipals(SSOUser.class);
            Iterator i = principals.iterator();
            while (i.hasNext()) {
                ssoUser = (SSOUser) i.next();
                break;
            }

            // Make the cache aware of the user-session association so that
            // it can handle correctly cache entry lookups.
            //_cachePolicy.attachSessionToUser(principal, ssoUser);

            // Instead of associating the Principal used for authenticating (which is a
            // session id), sets the authenticated principal to the SSOUser part of the
            // Subject returned by the Gateway.
            JBossSecurityAssociationActions.setPrincipalInfo(ssoUser, passwordChars, subject);

            // Get the CallerPrincipal mapping
            RealmMapping realmMapping = (RealmMapping) securityCtx.lookup("realmMapping");
            Principal oldPrincipal = ssoUser;
            principal = realmMapping.getPrincipal(oldPrincipal);
            logger.debug("Mapped from input principal: " + oldPrincipal + "to: " + principal);
            if (principal.equals(oldPrincipal) == false) {
                _userPrincipalMap.put(principal, oldPrincipal);
            }

        } else {
            principal = null;
            logger.debug("User: " + username + " is NOT authenticated");
        }
    } catch (NamingException e) {
        principal = null;
        logger.error("Error during authenticate", e);
    }
    logger.debug("End authenticate, principal=" + ssoUser);
    return ssoUser;
}