Example usage for java.security.acl Group addMember

List of usage examples for java.security.acl Group addMember

Introduction

In this page you can find the example usage for java.security.acl Group addMember.

Prototype

public boolean addMember(Principal user);

Source Link

Document

Adds the specified member to the group.

Usage

From source file:org.betaconceptframework.astroboa.test.engine.security.CmsLoginTest.java

@Test
public void testAuthorizedRepositoriesAreTheSameFoundInSubject() {

    Subject subject = new Subject();

    String identity = "testuser";
    subject.getPrincipals().add(new IdentityPrincipal(identity));

    Group group = new CmsGroup(AstroboaPrincipalName.AuthorizedRepositories.toString());
    group.addMember(new CmsPrincipal("testRepositoryA"));
    group.addMember(new CmsPrincipal("testRepositoryB"));
    group.addMember(new CmsPrincipal(TestConstants.TEST_REPOSITORY_ID));

    subject.getPrincipals().add(group);//  w w w . jav  a 2  s  .  c om

    repositoryService.login(TestConstants.TEST_REPOSITORY_ID, subject, null);

    SecurityContext securityContext = AstroboaClientContextHolder.getActiveSecurityContext();

    Assert.assertNotNull(securityContext, "Found no security context in Thread for logged in user " + identity);

    List<String> authorizedRepositories = securityContext.getAuthorizedRepositories();

    Assert.assertTrue(CollectionUtils.isNotEmpty(authorizedRepositories),
            "Authorized repositories must not be empty");

    Assert.assertTrue(authorizedRepositories.size() == 3,
            "Authorized repositories must be exactly 3. " + authorizedRepositories.toString());

    for (String repositoryId : authorizedRepositories) {
        Assert.assertTrue(
                repositoryId.equals("testRepositoryA") || repositoryId.equals("testRepositoryB")
                        || repositoryId.equals(TestConstants.TEST_REPOSITORY_ID),
                "Repository id " + repositoryId + " must not exist in authorized repositories "
                        + authorizedRepositories.toString());
    }

}

From source file:org.nuxeo.ecm.platform.login.test.DummyNuxeoLoginModule.java

/**
 * Gets the roles the user belongs to./*  w  w  w .  j ava 2  s . c o m*/
 */
@Override
protected Group[] getRoleSets() throws LoginException {

    String username = identity.getName();
    List<String> roles = identity.getRoles();

    Group roleSet = new GroupImpl("Roles");
    log.debug("Getting roles for user=" + username);
    for (String roleName : roles) {
        Principal role = new PrincipalImpl(roleName);
        log.debug("Found role=" + roleName);
        roleSet.addMember(role);
    }
    Group callerPrincipal = new GroupImpl("CallerPrincipal");
    callerPrincipal.addMember(identity);

    return new Group[] { roleSet, callerPrincipal };
}

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

private void setupContextForInternalIdentityStore(String identityStoreRepositoryId) {

    //Since we are using the internal identity store, we must setup the security context
    //for the user who will be used to connect to the repository which represents the
    //identity store. This user is the SYSTEM user by default and thus we perform
    //an internal login without the need of the SYSTEM's password
    Subject subject = new Subject();

    //System identity
    subject.getPrincipals().add(new IdentityPrincipal(IdentityPrincipal.SYSTEM));

    //Grant SYSTEM all roles
    Group rolesPrincipal = new CmsGroup(AstroboaPrincipalName.Roles.toString());

    for (CmsRole cmsRole : CmsRole.values()) {
        rolesPrincipal.addMember(new CmsPrincipal(CmsRoleAffiliationFactory.INSTANCE
                .getCmsRoleAffiliationForRepository(cmsRole, identityStoreRepositoryId)));
    }/* w ww  .  java 2s .c o m*/
    subject.getPrincipals().add(rolesPrincipal);

    //Login using the Subject, the provided roles and SYSTEM's permanent key and get the authentication token
    authenticationTokenForSYSTEMofInternalIdentityStore = repositoryDao.login(identityStoreRepositoryId,
            subject, RepositoryRegistry.INSTANCE.getPermanentKeyForUser(identityStoreRepositoryId,
                    IdentityPrincipal.SYSTEM));

}

From source file:org.nuxeo.ecm.platform.login.NuxeoLoginModule.java

/**
 * Gets the roles the user belongs to.//from ww w  .ja  v a 2s.  com
 */
@Override
protected Group[] getRoleSets() throws LoginException {
    log.debug("getRoleSets");
    if (manager == null) {
        // throw new LoginException("UserManager implementation not found");
    }
    String username = identity.getName();
    List<String> roles = identity.getRoles();

    Group roleSet = new GroupImpl("Roles");
    log.debug("Getting roles for user=" + username);
    for (String roleName : roles) {
        Principal role = new PrincipalImpl(roleName);
        log.debug("Found role=" + roleName);
        roleSet.addMember(role);
    }
    Group callerPrincipal = new GroupImpl("CallerPrincipal");
    callerPrincipal.addMember(identity);

    return new Group[] { roleSet, callerPrincipal };
}

From source file:org.jasig.cas.client.jaas.CasLoginModule.java

public boolean commit() throws LoginException {
    if (this.assertion != null) {
        if (this.ticket != null) {
            this.subject.getPrivateCredentials().add(this.ticket);
        } else {/*from   www.ja  v  a 2s  .c  o  m*/
            throw new LoginException("Ticket credential not found.");
        }

        final AssertionPrincipal casPrincipal = new AssertionPrincipal(this.assertion.getPrincipal().getName(),
                this.assertion);
        this.subject.getPrincipals().add(casPrincipal);

        // Add group containing principal as sole member
        // Supports JBoss JAAS use case
        final Group principalGroup = new SimpleGroup(this.principalGroupName);
        principalGroup.addMember(casPrincipal);
        this.subject.getPrincipals().add(principalGroup);

        // Add group principal containing role data
        final Group roleGroup = new SimpleGroup(this.roleGroupName);
        for (int i = 0; i < defaultRoles.length; i++) {
            roleGroup.addMember(new SimplePrincipal(defaultRoles[i]));
        }
        final Map attributes = this.assertion.getPrincipal().getAttributes();
        final Iterator nameIterator = attributes.keySet().iterator();
        while (nameIterator.hasNext()) {
            final Object key = nameIterator.next();
            if (this.roleAttributeNames.contains(key)) {
                // Attribute value is Object if singular or Collection if plural
                final Object value = attributes.get(key);
                if (value instanceof Collection) {
                    final Iterator valueIterator = ((Collection) value).iterator();
                    while (valueIterator.hasNext()) {
                        roleGroup.addMember(new SimplePrincipal(valueIterator.next().toString()));
                    }
                } else {
                    roleGroup.addMember(new SimplePrincipal(value.toString()));
                }
            }
        }
        this.subject.getPrincipals().add(roleGroup);

        // Place principal name in shared state for downstream JAAS modules (module chaining use case)
        this.sharedState.put(LOGIN_NAME, casPrincipal.getName());

        if (log.isDebugEnabled()) {
            if (log.isDebugEnabled()) {
                log.debug("Created JAAS subject with principals: " + subject.getPrincipals());
            }
        }

        if (this.cacheAssertions) {
            if (log.isDebugEnabled()) {
                log.debug("Caching assertion for principal " + this.assertion.getPrincipal());
            }
            ASSERTION_CACHE.put(this.ticket, this.assertion);
        }
    } else {
        // Login must have failed if there is no assertion defined
        // Need to clean up state
        if (this.ticket != null) {
            this.ticket = null;
        }
    }
    return true;
}

From source file:org.betaconceptframework.astroboa.security.jaas.AstroboaLoginModule.java

private void initializeAstroboaClientForIdentityStore(String identityStoreRepositoryId) {

    //We assume that identity store repository exists in the same Astroboa server this module runs
    AstroboaClient clientForInternalIdentityStore = new AstroboaClient();

    //Login as SYSTEM using Subject in order to avoid calling JAAS again
    //TODO This must be handled differently
    //In order to connect to IdentityStore, one must connect only as SYSTEM for now
    Subject subject = new Subject();

    //System identity
    subject.getPrincipals().add(new IdentityPrincipal(IdentityPrincipal.SYSTEM));

    Group rolesPrincipal = new CmsGroup(AstroboaPrincipalName.Roles.toString());

    for (CmsRole cmsRole : CmsRole.values()) {
        rolesPrincipal.addMember(new CmsPrincipal(CmsRoleAffiliationFactory.INSTANCE
                .getCmsRoleAffiliationForRepository(cmsRole, identityStoreRepositoryId)));
    }/* w  w  w  .  j a v  a2 s  .  c  o m*/

    subject.getPrincipals().add(rolesPrincipal);

    clientForInternalIdentityStore.login(identityStoreRepositoryId, subject, RepositoryRegistry.INSTANCE
            .getPermanentKeyForUser(identityStoreRepositoryId, IdentityPrincipal.SYSTEM));

    identityStore = clientForInternalIdentityStore.getIdentityStore();
}

From source file:org.josso.jb32.agent.JBossCatalinaNativeRealm.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 Gateway
 * as the authenticatd Principal./* www. j a  va2s. c om*/
 * 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
 */
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();

        SSOIdentityManagerService im = Lookup.getInstance().lookupSSOAgent().getSSOIdentityManager();

        String requester = "";
        // Check for nulls ?
        SSOAgentRequest request = AbstractSSOAgent._currentRequest.get();
        if (request != null)
            requester = request.getRequester();
        else
            logger.warn("No SSO Agent request found in thread local variable, can't identify requester");

        ssoUser = im.findUserInSession(requester, username);

        if (ssoUser != null) {
            logger.debug("User: " + username + " is authenticated");

            Subject subject = new Subject();
            subject.getPrincipals().add(ssoUser);
            logger.warn("WARN Cannot identify requester!");
            SSORole[] ssoRolePrincipals = im.findRolesBySSOSessionId(requester, username);
            Group targetGrp = new BaseRoleImpl("Roles");
            for (int i = 0; i < ssoRolePrincipals.length; i++) {
                subject.getPrincipals().add(ssoRolePrincipals[i]);
                targetGrp.addMember(ssoRolePrincipals[i]); // Add user role to "Roles" group
            }
            // Add the "Roles" group to the Subject so that JBoss can fetch user roles.
            subject.getPrincipals().add(targetGrp);

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

            // 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);
            if (!principal.equals(oldPrincipal)) {
                _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);
    } catch (SSOIdentityException e) {
        // Ignore this ... (user does not exist for this session)
        if (logger.isDebugEnabled()) {
            logger.debug(e.getMessage());
        }
        principal = null;
    } catch (Exception e) {
        logger.error("Session authentication failed : " + username, e);
        throw new RuntimeException("Fatal error authenticating session : " + e);
    }
    logger.debug("End authenticate, principal=" + ssoUser);
    return ssoUser;
}

From source file:org.josso.jb4.agent.JBossCatalinaNativeRealm.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 Gateway
 * as the authenticatd Principal.//from www .j av a 2s  . co  m
 * 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
 */
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();

        SSOIdentityManagerService im = Lookup.getInstance().lookupSSOAgent().getSSOIdentityManager();

        String requester = "";
        // Check for nulls ?
        SSOAgentRequest request = AbstractSSOAgent._currentRequest.get();
        if (request != null)
            requester = request.getRequester();
        else
            logger.warn("No SSO Agent request found in thread local variable, can't identify requester");

        ssoUser = im.findUserInSession(requester, username);

        if (ssoUser != null) {
            logger.debug("User: " + username + " is authenticated");

            Subject subject = new Subject();
            subject.getPrincipals().add(ssoUser);
            logger.warn("WARN Cannot identify requester!");
            SSORole[] ssoRolePrincipals = im.findRolesBySSOSessionId(requester, username);
            Group targetGrp = new BaseRoleImpl("Roles");
            for (int i = 0; i < ssoRolePrincipals.length; i++) {
                subject.getPrincipals().add(ssoRolePrincipals[i]);
                targetGrp.addMember(ssoRolePrincipals[i]); // Add user role to "Roles" group
            }
            // Add the "Roles" group to the Subject so that JBoss can fetch user roles.
            subject.getPrincipals().add(targetGrp);

            Group callerPrincipal = new BaseRoleImpl("CallerPrincipal");
            callerPrincipal.addMember(ssoUser);
            // Add the "CallerPrincipal" group to the Subject so that JBoss can fetch user.
            subject.getPrincipals().add(callerPrincipal);

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

            // 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);
    } catch (SSOIdentityException e) {
        // Ignore this ... (user does not exist for this session)
        if (logger.isDebugEnabled()) {
            logger.debug(e.getMessage());
        }
        principal = null;
    } catch (Exception e) {
        logger.error("Session authentication failed : " + username, e);
        throw new RuntimeException("Fatal error authenticating session : " + e);
    }
    logger.debug("End authenticate, principal=" + ssoUser);
    return ssoUser;
}

From source file:org.nuxeo.ecm.platform.login.NuxeoAbstractServerLoginModule.java

public boolean commit() throws LoginException {
    log.trace("commit, loginOk=" + loginOk);
    if (!loginOk) {
        return false;
    }/*from w w w. j a  v a  2 s.  c om*/

    Set<Principal> principals = subject.getPrincipals();
    Principal identity = getIdentity();
    principals.add(identity);
    Group[] roleSets = getRoleSets();
    for (Group group : roleSets) {
        String name = group.getName();
        Group subjectGroup = createGroup(name, principals);

        /*
         * if( subjectGroup instanceof NestableGroup ) { SimpleGroup tmp = new SimpleGroup("Roles");
         * subjectGroup.addMember(tmp); subjectGroup = tmp; }
         */

        // Copy the group members to the Subject group
        Enumeration<? extends Principal> members = group.members();
        while (members.hasMoreElements()) {
            Principal role = members.nextElement();
            subjectGroup.addMember(role);
        }
    }
    return true;
}

From source file:org.betaconceptframework.astroboa.context.SecurityContext.java

public boolean addRole(String role) {

    if (StringUtils.isBlank(role)) {
        return false;
    }/*w ww . j  ava2s. c o  m*/

    Set<Group> groups = subject.getPrincipals(Group.class);

    boolean roleGroupFound = false;

    boolean roleAdded = false;

    String nameOfGroupWhichContainsTheRoles = AstroboaPrincipalName.Roles.toString();

    if (groups != null) {

        for (Group group : groups) {
            if (StringUtils.equals(nameOfGroupWhichContainsTheRoles, group.getName())) {
                roleGroupFound = true;

                final CmsPrincipal rolePrincipal = new CmsPrincipal(role);
                if (!group.isMember(rolePrincipal)) {
                    group.addMember(rolePrincipal);
                    roleAdded = true;
                }

                break;
            }
        }
    }

    if (!roleGroupFound) {
        Group rolesPrincipal = new CmsGroup(nameOfGroupWhichContainsTheRoles);
        rolesPrincipal.addMember(new CmsPrincipal(role));
        subject.getPrincipals().add(rolesPrincipal);
        roleAdded = true;
    }

    if (roleAdded) {
        this.roles.add(role);
    }

    return roleAdded;
}