private static String getUseridFromJAASSubject() { Subject subject = Subject.getSubject(AccessController.getContext()); LOGGER.trace("Subject of caller: {}", subject); if (subject != null) { Set<Principal> principals = subject.getPrincipals(); LOGGER.trace("Public principals of caller: {}", principals); for (Principal pC : principals) { if (!(pC instanceof Group)) { String userIdFound = pC.getName(); String userIdUsed = userIdFound; if (TaskanaEngineConfiguration.shouldUseLowerCaseForAccessIds() && userIdFound != null) { userIdUsed = userIdFound.toLowerCase(); } LOGGER.trace("Found User id {}. Returning User id {} ", userIdFound, userIdUsed); return userIdUsed; } } } LOGGER.trace("No userid found in subject!"); return null; }
public static List<String> getGroupIds() { Subject subject = Subject.getSubject(AccessController.getContext()); LOGGER.trace("Subject of caller: {}", subject); List<String> groupIds = new ArrayList<>(); if (subject != null) { Set<Group> groups = subject.getPrincipals(Group.class); LOGGER.trace("Public groups of caller: {}", groups); for (Principal group : groups) { String groupNameFound = group.getName(); String groupNameReturned = groupNameFound; if (TaskanaEngineConfiguration.shouldUseLowerCaseForAccessIds() && groupNameFound != null) { groupNameReturned = groupNameFound.toLowerCase(); } LOGGER.trace("Found group id {}. Returning group Id: {}", groupNameFound, groupNameReturned); groupIds.add(groupNameReturned); } return groupIds; } LOGGER.trace("No groupids found in subject!"); return groupIds; }
/** * Find or create a Group with the given name. Subclasses should use this method to locate the 'Roles' group or * create additional types of groups. * * @return A named Group from the principals set. */ private Group createGroup(String name, Set<Principal> principals) { Group roles = null; for (Principal principal : principals) { if (principal instanceof Group) { Group grp = (Group) principal; if (grp.getName().equals(name)) { roles = grp; break; } } } // If we did not find a group create one if (roles == null) { roles = new SimpleGroup(name); principals.add(roles); } return roles; }
public boolean checkPrincipal(Object identity) { if (identity != null && identity instanceof OIDCPrincipal) { super.loginOk = true; this.identity = (OIDCPrincipal) identity; Group roles = new SimpleGroup(SecurityConstants.ROLES_IDENTIFIER); if (identity != null && rolesClaimName != null) { Object rolesClaim = this.identity.getClaims().get(rolesClaimName); if (rolesClaim instanceof JSONArray) { ((List<String>) rolesClaim).forEach(r -> roles.addMember(new SimplePrincipal(r))); } } this.roleSets = new Group[] { roles }; return true; } return false; }
/** * Set session variables after user login * * @throws Exception */ private void postLogin(User user) { log.debug("Configuring application after user '{0}' login", user.getUid()); GluuCustomPerson person = findPersonByDn(user.getDn()); Contexts.getSessionContext().set(OxTrustConstants.CURRENT_PERSON, person); // Set user roles GluuUserRole[] userRoles = securityService.getUserRoles(user); if (ArrayHelper.isNotEmpty(userRoles)) { log.debug("Get '{0}' user roles", Arrays.toString(userRoles)); } else { log.debug("Get 0 user roles"); } for (GluuUserRole userRole : userRoles) { identity.addRole(userRole.getRoleName()); } if (log.isDebugEnabled()) { for (Group sg : identity.getSubject().getPrincipals(java.security.acl.Group.class)) { if ("Roles".equals(sg.getName())) { log.debug("Using next user roles: '{0}'", sg.members()); break; } } } }
@Override public boolean equals(Object obj) { if (this == obj) return true; if (super.equals(obj)) return true; if (!Group.class.isAssignableFrom(obj.getClass())) return false; Group other = (Group) obj; String otherGroupName = other.getName(); if(otherGroupName == null) return false; if (primaryLdapGroupName == null) return false; return primaryLdapGroupName.equals(otherGroupName); }
@Override public Boolean apply(Principal obj) { if (this == obj) return true; if (super.equals(obj)) return true; if (!Group.class.isAssignableFrom(obj.getClass())) return false; Group other = (Group) obj; String otherGroupName = other.getName(); if(otherGroupName == null) return false; if (primaryLdapGroupName == null) return false; return primaryLdapGroupName.equals(otherGroupName); }
public static String[] getRoles(Subject subject, String[] defalt) { ArrayList<String> roles = new ArrayList<String>(); Set<Group> principals = subject.getPrincipals(Group.class); if ((principals != null) && (principals.size() > 0)) { for (Group group : principals) { if (group.getName().equalsIgnoreCase("roles")) { //$NON-NLS-1$ Enumeration<? extends Principal> members = group.members(); while(members.hasMoreElements()) { Principal member = members.nextElement(); roles.add(member.getName()); } } } return roles.toArray(new String[roles.size()]); } return defalt; }
private Set<String> getUserRoles() { if (getSubject() == null) { return Collections.emptySet(); } Set<String> roles = new HashSet<String>(); Set<Principal> principals = getSubject().getPrincipals(); for(Principal p: principals) { // this JBoss specific, but no code level dependencies if ((p instanceof Group) && p.getName().equals("Roles")){ //$NON-NLS-1$ Group g = (Group)p; Enumeration<? extends Principal> rolesPrinciples = g.members(); while(rolesPrinciples.hasMoreElements()) { roles.add(rolesPrinciples.nextElement().getName()); } } } return roles; }
/** * {@inheritDoc} */ @Override public Principal getCallerPrincipal(String securityDomain) { Principal callerPrincipal = null; Subject subject = getSubject(securityDomain, false); if (subject != null) { outerLoop : for (Principal principal : subject.getPrincipals()) { if (principal instanceof Group) { Group group = (Group)principal; if (group.getName().equalsIgnoreCase(CALLER_PRINCIPAL)) { Enumeration<? extends Principal> members = group.members(); while (members.hasMoreElements()) { callerPrincipal = members.nextElement(); break outerLoop; } } } else if (callerPrincipal == null && principal != null) { // the second case (the simple name comparison) is here to support Karaf if (principal instanceof UserPrincipal || principal.getClass().getSimpleName().equals("UserPrincipal")) { callerPrincipal = principal; } } } } return callerPrincipal; }
/** * {@inheritDoc} */ @Override public boolean isCallerInRole(String roleName, String securityDomain) { Subject subject = getSubject(securityDomain, false); if (subject != null) { for (Principal principal : subject.getPrincipals()) { if (principal instanceof Group) { Group group = (Group)principal; if (group.getName().equalsIgnoreCase(ROLES)) { Enumeration<? extends Principal> roles = group.members(); while (roles.hasMoreElements()) { Principal role = roles.nextElement(); if (role.getName().equals(roleName)) { return true; } } } } } } return false; }
/** * Transfers Principals, private credentials, and public credentials from one Subject to another. * @param fromSubject the from Subject * @param toSubject the to Subject */ protected void transfer(Subject fromSubject, Subject toSubject) { if (toSubject != null && fromSubject != null && toSubject != fromSubject && !toSubject.equals(fromSubject)) { Set<Principal> toPrincipals = toSubject.getPrincipals(); Group toRolesGroup = null; for (Principal fromPrincipal : fromSubject.getPrincipals()) { if (fromPrincipal instanceof Group && GroupPrincipal.ROLES.equals(fromPrincipal.getName())) { Group fromRolesGroup = (Group)fromPrincipal; if (toRolesGroup == null) { toRolesGroup = getRolesGroup(toSubject); } if (toRolesGroup == fromRolesGroup) { continue; } for (Principal fromRole : Collections.list(fromRolesGroup.members())) { RolePrincipal toRole = fromRole instanceof RolePrincipal ? (RolePrincipal)fromRole : new RolePrincipal(fromRole.getName()); toRolesGroup.addMember(toRole); } } else { toPrincipals.add(fromPrincipal); } } toSubject.getPrivateCredentials().addAll(fromSubject.getPrivateCredentials()); toSubject.getPublicCredentials().addAll(fromSubject.getPublicCredentials()); } }
/** * Gets the Group with the name "Roles" from the specified Subject, creating one if not pre-existent. * @param subject the subject * @return the "Roles" Group */ private Group getRolesGroup(Subject subject) { Group rolesGroup = null; Set<Group> groups = subject.getPrincipals(Group.class); for (Group group : groups) { if (GroupPrincipal.ROLES.equals(group.getName())) { rolesGroup = group; break; } } if (rolesGroup == null) { rolesGroup = new GroupPrincipal(GroupPrincipal.ROLES); subject.getPrincipals().add(rolesGroup); } return rolesGroup; }
private Set<Group> getGroupMembership(Authorizable authorizable) { Set<java.security.acl.Group> groupPrincipals = new HashSet<Group>(); try { Iterator<org.apache.jackrabbit.api.security.user.Group> groups = authorizable.memberOf(); while (groups.hasNext()) { Principal grPrincipal = groups.next().getPrincipal(); if (grPrincipal instanceof Group) { groupPrincipals.add((Group) grPrincipal); } } } catch (RepositoryException e) { log.debug(e.getMessage()); } groupPrincipals.add(EveryonePrincipal.getInstance()); return groupPrincipals; }
/** Find or create a Group with the given name. Subclasses should use this method to locate the 'Roles' group or create additional types of groups. @return A named Group from the principals set. */ protected Group createGroup(String name, Set<Principal> principals) { Group roles = null; Iterator<Principal> iter = principals.iterator(); while( iter.hasNext() ) { Object next = iter.next(); if( (next instanceof Group) == false ) continue; Group grp = (Group) next; if( grp.getName().equals(name) ) { roles = grp; break; } } // If we did not find a group create one if( roles == null ) { roles = new SimpleGroup(name); principals.add(roles); } return roles; }
protected Group getCallerPrincipalGroup(Set<Principal> principals) { Group callerGroup = null; for (Principal principal : principals) { if (principal instanceof Group) { Group group = Group.class.cast(principal); if (group.getName().equals(SecurityConstants.CALLER_PRINCIPAL_GROUP)) { callerGroup = group; break; } } } return callerGroup; }
/** * Get the Group called as "Roles" from the authenticated subject * * @return Group representing Roles */ private Group getExistingRolesFromSubject() { Iterator<? extends Principal> iter = subject.getPrincipals().iterator(); while(iter.hasNext()) { Principal p = iter.next(); if(p instanceof Group) { Group g = (Group) p; if("Roles".equals(g.getName())) return g; } } return null; }
/** * Process the group with the roles that are mapped in the * properies file * @param group Group that needs to be processed * @param props Properties file */ private void processRoles(Group group,Properties props) //throws Exception { Enumeration<?> enumer = props.propertyNames(); while(enumer.hasMoreElements()) { String roleKey = (String)enumer.nextElement(); String comma_separated_roles = props.getProperty(roleKey); try { Principal pIdentity = createIdentity(roleKey); if (group != null) { if(group.isMember(pIdentity)) Util.parseGroupMembers(group,comma_separated_roles,this); if(REPLACE_ROLE) group.removeMember(pIdentity); } } catch(Exception e) { PicketBoxLogger.LOGGER.debugFailureToCreatePrincipal(roleKey, e); } } }
/** Parse the comma delimited roles names given by value and add them to * group. The type of Principal created for each name is determined by * the createIdentity method. * * @see AbstractServerLoginModule#createIdentity(String) * * @param group - the Group to add the roles to. * @param roles - the comma delimited role names. */ static void parseGroupMembers(Group group, String roles, AbstractServerLoginModule aslm) { StringTokenizer tokenizer = new StringTokenizer(roles, ","); while (tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); try { Principal p = aslm.createIdentity(token); group.addMember(p); } catch (Exception e) { PicketBoxLogger.LOGGER.debugFailureToCreatePrincipal(token, e); } } }
public String[] getRoleNames(String roleGroup) { Group group = roleGroups.get(roleGroup); String[] names = {}; if( group != null ) { ArrayList<String> tmp = new ArrayList<String>(); Enumeration<? extends Principal> iter = group.members(); while( iter.hasMoreElements() ) { Principal p = iter.nextElement(); tmp.add(p.getName()); } names = new String[tmp.size()]; tmp.toArray(names); } return names; }
/** Overridden by subclasses to return the Groups that correspond to the to the role sets assigned to the user. Subclasses should create at least a Group named "Roles" that contains the roles assigned to the user. A second common group is "CallerPrincipal" that provides the application identity of the user rather than the security domain identity. @return Group[] containing the sets of roles */ protected Group[] getRoleSets() throws LoginException { // SECURITY-225: check if authentication was already done in a previous login module // and perform role mapping if (!isPasswordValidated && getIdentity() != unauthenticatedIdentity) { try { String username = getUsername(); PicketBoxLogger.LOGGER.traceBindingLDAPUsername(username); createLdapInitContext(username, null); defaultRole(); } catch (Exception e) { LoginException le = new LoginException(); le.initCause(e); throw le; } } Group[] roleSets = {userRoles}; return roleSets; }
/** * Get the Subject roles by looking for a Group called 'Roles' * * @param theSubject - the Subject to search for roles * @return the Group contain the subject roles if found, null otherwise */ public static Group getSubjectRoles(Subject theSubject) { if (theSubject == null) throw PicketBoxMessages.MESSAGES.invalidNullArgument("theSubject"); Set<Group> subjectGroups = theSubject.getPrincipals(Group.class); Iterator<Group> iter = subjectGroups.iterator(); Group roles = null; while (iter.hasNext()) { Group grp = iter.next(); String name = grp.getName(); if (name.equals("Roles")) roles = grp; } return roles; }
/** * Get the Subject roles by looking for a Group called 'Roles' * @param theSubject - the Subject to search for roles * @return the Group contain the subject roles if found, null otherwise */ private Group getGroupFromSubject(Subject theSubject) { if(theSubject == null) throw PicketBoxMessages.MESSAGES.invalidNullArgument("theSubject"); Set<Group> subjectGroups = theSubject.getPrincipals(Group.class); Iterator<Group> iter = subjectGroups.iterator(); Group roles = null; while( iter.hasNext() ) { Group grp = iter.next(); String name = grp.getName(); if( name.equals(ROLES_IDENTIFIER) ) roles = grp; } return roles; }
@Override public <T> void set(String key, T obj) { validateSecurityContext(); if(key == null) throw PicketBoxMessages.MESSAGES.invalidNullArgument("key"); if(obj != null) { if(RUNAS_IDENTITY_IDENTIFIER.equals(key) && obj instanceof RunAsIdentity == false) throw PicketBoxMessages.MESSAGES.invalidType(RunAsIdentity.class.getName()); if(ROLES_IDENTIFIER.equals(key) && obj instanceof Group == false) throw PicketBoxMessages.MESSAGES.invalidType(Group.class.getName()); } if(RUNAS_IDENTITY_IDENTIFIER.equals(key)) setRunAsIdentity( (RunAsIdentity) obj); else securityContext.getData().put(key, obj); }
/** Test of addMember method, of class org.jboss.security.NestableGroup. */ public void testAddMember() { System.out.println("testAddMember"); for(int g = 0; g < groups.length; g ++) { Group grp = groups[g]; group.addMember(grp); testMembers(g); } try { group.addMember(new SimplePrincipal("BadGroup")); fail("Was able to add a Principal to NestableGroup"); } catch(IllegalArgumentException e) { } }
public int authorize(Resource resource) { Set<Principal> principals = subject.getPrincipals(); for(Principal p: principals) { if(p instanceof Group) { Group group = (Group) p; if(group.getName().equalsIgnoreCase("Roles")) { Enumeration<? extends Principal> roles = group.members(); while(roles.hasMoreElements()) { Principal role = roles.nextElement(); if(rolesSet.contains(role.getName())) return AuthorizationContext.PERMIT; } } } } return AuthorizationContext.DENY; }
/** * Adds a role to the authenticated user. * * @param role * The name of the role to add */ public boolean addRole(String role) { if (role == null || "".equals(role)) { return false; } if (!isLoggedIn()) { return false; } else { for (Group sg : getSubject().getPrincipals(Group.class)) { if (ROLES_GROUP.equals(sg.getName())) { return sg.addMember(new Role(role)); } } SimpleGroup roleGroup = new SimpleGroup(ROLES_GROUP); roleGroup.addMember(new Role(role)); getSubject().getPrincipals().add(roleGroup); return true; } }
public void addUserToGroup(int userId, int groupId) throws RedmineException { logger.debug("adding user " + userId + " to group " + groupId + "..."); URI uri = getURIConfigurator().getChildObjectsURI(Group.class, Integer.toString(groupId), User.class); HttpPost httpPost = new HttpPost(uri); final StringWriter writer = new StringWriter(); final JSONWriter jsonWriter = new JSONWriter(writer); try { jsonWriter.object().key("user_id").value(userId).endObject(); } catch (JSONException e) { throw new RedmineInternalError("Unexpected exception", e); } String body = writer.toString(); setEntity(httpPost, body); String response = getCommunicator().sendRequest(httpPost); logger.debug(response); return; }
@Override protected void authorize(LoginContext context) throws LoginException { HashSet<String> required = new HashSet<>(requiredRoles); Set<Group> groups = context.getSubject().getPrincipals(Group.class); if (groups != null) { for (Group group : groups) { if ("Roles".equals(group.getName())) { for (String role : requiredRoles) { if (group.isMember(new SimplePrincipal(role))) { required.remove(role); } } } } } if (!required.isEmpty()) throw new LoginException("User does not have required roles: " + required); }
protected ContributorPrincipal fixPrincipal() { log.log(Level.FINEST, "Remove CAS principal and default group. Assertion name: {0}", this.assertion.getPrincipal().getName()); this.subject.getPrincipals().remove(new AssertionPrincipal(this.assertion.getPrincipal().getName(), this.assertion)); this.subject.getPrincipals().remove(new SimpleGroup(this.principalGroupName)); log.log(Level.FINEST, "Add ContributorPrincipal"); final ContributorPrincipal contributorPrincipal = new ContributorPrincipal(this.assertion.getPrincipal().getName(), this.assertion); this.subject.getPrincipals().add(contributorPrincipal); final Group principalGroup = new SimpleGroup(this.principalGroupName); principalGroup.addMember(contributorPrincipal); this.subject.getPrincipals().add(principalGroup); return contributorPrincipal; }
/** * Method to commit the authentication process (phase 2). */ @Override public boolean commit() throws LoginException { if (loginOK == false) { return false; } /* * If the login method completed successfully as indicated by * loginOK == true, this method adds the identity value to the subject's principals set. It also adds the * members of * each Group returned by getRoleSets() to the subject's principals Set. */ Set<Principal> principals = subject.getPrincipals(); principals.add(identity); for (Group group : getRoleSets()) { String name = group.getName(); Group subjectGroup = createGroup(name, principals); // Copy the group members to the Subject group Enumeration<? extends Principal> members = group.members(); while (members.hasMoreElements()) { Principal role = members.nextElement(); subjectGroup.addMember(role); } } UniversalLoginModule.log.info("User logged in: " + getUserName()); return true; }
/** * Obtiene roles usuario (modificado para que no llame a createIdentity al crear cada role) */ protected Group[] getRoleSets() throws LoginException { Principal principal = getIdentity (); if ( ! (principal instanceof MockPrincipal) ) { if (log.isTraceEnabled()) log.trace("Principal "+principal+" not a MockPrincipal"); return new Group[0]; } String username = getUsername(); List roles = null; try { roles = getUserRoles(username); } catch (Exception e) { log.error("Excepcion obteniendo roles",e); throw new LoginException("Excepcion obteniendo roles"); } Group rolesGroup = new SimpleGroup("Roles"); for (Iterator iterator = roles.iterator();iterator.hasNext();){ String roleName = (String) iterator.next(); rolesGroup.addMember(new SimplePrincipal(roleName)); } HashMap setsMap = new HashMap(); setsMap.put("Roles", rolesGroup); // Montamos grupo "CallerPrincipal" Group principalGroup = new SimpleGroup("CallerPrincipal"); principalGroup.addMember(principal); setsMap.put("CallerPrincipal", principalGroup); // Devolvemos respuesta Group roleSets[] = new Group[setsMap.size()]; setsMap.values().toArray(roleSets); return roleSets; }
/** * Extract the Roles group and return it as a RoleGroup * * @param subject authenticated subject * @return RoleGroup from "Roles" */ protected RoleGroup extract(Subject subject) { Optional<Principal> match = subject.getPrincipals() .stream() .filter(g -> g.getName().equals(SecurityConstants.ROLES_IDENTIFIER)) .findFirst(); Group rolesGroup = (Group) match.get(); RoleGroup roles = new SimpleRoleGroup(rolesGroup); return roles; }
private Set<String> getRoles(Subject subject) { Set<String> roles = new HashSet<String>(); for (Principal principal : subject.getPrincipals()) { if (principal instanceof Group) { for (Enumeration<? extends Principal> members = ((Group)principal).members(); members.hasMoreElements();) { roles.add(members.nextElement().getName()); } } } return roles; }
@Override protected Group[] getRoleSets() throws LoginException { log.debug("Retrieving Groups"); HttpServletRequest request = null; try { request = (HttpServletRequest) PolicyContext.getContext("javax.servlet.http.HttpServletRequest"); } catch (PolicyContextException e) { log.error("Could not load HttpServletRequest", e); return null; } if (request == null) { return null; } Attribute attr = (Attribute) request.getAttribute("UINSON_ROLES"); SimpleGroup group = new SimpleGroup("Roles"); if (attr != null) { for (String val : attr.getValues()) { group.addMember(new SimplePrincipal(val)); } } if (log.isDebugEnabled()) { log.debug("Returning Groups : " + group); } return new Group[]{group}; }
public static Role getRoleGroup(final Subject subject) { final Set<Group> groups = subject.getPrincipals(Group.class); for (Group group : groups) { if ("Roles".equals(group.getName())) { return new SimpleRoleGroup(group); } } return null; }
private Subject createTestSubject() { Subject testSubject = new Subject(); UserPrincipal p = new UserPrincipal("demo"); testSubject.getPrincipals().add(p); p.putCustomProperty(UserPrincipal.LANGUAGE_PROPERTY, "en"); Group rolesGroup = new SimpleGroup(SecurityHelper.ROLES_GROUP_NAME); rolesGroup.addMember(new SimplePrincipal("administrator")); testSubject.getPrincipals().add(rolesGroup); return testSubject; }
/** * The constructor for the User class. Initializes the dynamic lists and managerDisplayname variables. */ public User(){ directReports = null; groups = new ArrayList<Group>(); roles = new ArrayList<Group>(); managerDisplayname = null; }