public Essence(DirContextOperations ctx) { super(ctx); setCarLicense(ctx.getStringAttribute("carLicense")); setDepartmentNumber(ctx.getStringAttribute("departmentNumber")); setDestinationIndicator(ctx.getStringAttribute("destinationIndicator")); setDisplayName(ctx.getStringAttribute("displayName")); setEmployeeNumber(ctx.getStringAttribute("employeeNumber")); setHomePhone(ctx.getStringAttribute("homePhone")); setHomePostalAddress(ctx.getStringAttribute("homePostalAddress")); setInitials(ctx.getStringAttribute("initials")); setMail(ctx.getStringAttribute("mail")); setMobile(ctx.getStringAttribute("mobile")); setO(ctx.getStringAttribute("o")); setOu(ctx.getStringAttribute("ou")); setPostalAddress(ctx.getStringAttribute("postalAddress")); setPostalCode(ctx.getStringAttribute("postalCode")); setRoomNumber(ctx.getStringAttribute("roomNumber")); setStreet(ctx.getStringAttribute("street")); setTitle(ctx.getStringAttribute("title")); setUid(ctx.getStringAttribute("uid")); }
private String getReferencedGroupValue(final DirContextOperations ctx) { final String referencedGroupValue; if (StringUtils.isBlank(userGroupReferencedGroupAttribute)) { referencedGroupValue = ctx.getDn().toString(); } else { final Attribute attributeName = ctx.getAttributes().get(userGroupReferencedGroupAttribute); if (attributeName == null) { throw new AuthorizationAccessException("Referenced group value attribute [" + userGroupReferencedGroupAttribute + "] does not exist."); } try { referencedGroupValue = (String) attributeName.get(); } catch (NamingException e) { throw new AuthorizationAccessException("Error while retrieving referenced group value attribute [" + userGroupReferencedGroupAttribute + "]."); } } return referencedGroupValue; }
@Override public UserDetails mapUserFromContext(DirContextOperations ctx, String username, Collection<? extends GrantedAuthority> authorities) { String dn = ctx.getNameInNamespace(); essence.setDn(dn); Object passwordValue = ctx.getObjectAttribute(this.passwordAttributeName); String[] rolesForAttribute = ctx.getStringAttributes(this.roleAttributes[i]); .getObjectAttribute(PasswordPolicyControl.OID);
public Essence(DirContextOperations ctx) { super(ctx); setCn(ctx.getStringAttributes("cn")); setGivenName(ctx.getStringAttribute("givenName")); setSn(ctx.getStringAttribute("sn")); setDescription(ctx.getStringAttribute("description")); setTelephoneNumber(ctx.getStringAttribute("telephoneNumber")); Object passo = ctx.getObjectAttribute("userPassword"); if (passo != null) { String password = LdapUtils.convertPasswordToString(passo); setPassword(password); } }
/** * {@inheritDoc} */ @Override public void modifyAttributes(DirContextOperations ctx) { Name dn = ctx.getDn(); if (dn != null && ctx.isUpdateMode()) { modifyAttributes(dn, ctx.getModificationItems()); } else { throw new IllegalStateException("The DirContextOperations instance needs to be properly initialized."); } }
@Override public UserOrg doMapFromContext(final DirContextOperations context) { final UserOrg user = new UserOrg(); user.setDn(context.getDn().toString()); user.setLastName(context.getStringAttribute(SN_ATTRIBUTE)); user.setFirstName(context.getStringAttribute(GIVEN_NAME_ATTRIBUTE)); user.setSecured(context.getObjectAttribute(PASSWORD_ATTRIBUTE) != null); user.setId(Normalizer.normalize(context.getStringAttribute(uidAttribute))); // Special and also optional attributes Optional.ofNullable(departmentAttribute).ifPresent(a -> user.setDepartment(context.getStringAttribute(a))); Optional.ofNullable(localIdAttribute).ifPresent(a -> user.setLocalId(context.getStringAttribute(a))); Optional.ofNullable(lockedAttribute).ifPresent(a -> fillLockedData(user, context.getStringAttribute(a))); // Save the normalized CN of the company user.setCompany(toCompany(user.getDn())); if (context.attributeExists(PWD_ACCOUNT_LOCKED_ATTRIBUTE)) { user.setLockedBy(PPOLICY_NAME); user.setLocked(parseLdapDate(context.getStringAttribute(PWD_ACCOUNT_LOCKED_ATTRIBUTE))); } // Save the mails user.setMails( new ArrayList<>(CollectionUtils.emptyIfNull(context.getAttributeSortedStringSet(MAIL_ATTRIBUTE)))); return user; }
public LdapEntryIdentification mapFromContext(Object ctx) { DirContextOperations adapter = (DirContextOperations) ctx; return new LdapEntryIdentification( LdapUtils.newLdapName(adapter.getNameInNamespace()), LdapUtils.newLdapName(adapter.getDn())); } }
public Essence(DirContextOperations ctx) { setDn(ctx.getDn()); }
@Override protected User doMapFromContext(DirContextOperations ctx) { LdapUser user = new LdapUser(ctx.getDn().toString()); user.setFirstname(ctx.getStringAttribute(LDAP_ATTRIBUTE_GIVENNAME)); user.setLastname(ctx.getStringAttribute(LDAP_ATTRIBUTE_SURNAME)); user.setEmail(ctx.getStringAttribute(LDAP_ATTRIBUTE_MAIL)); user.setDisplayName(ctx.getStringAttribute(LDAP_ATTRIBUTE_DISPLAYNAME)); //user.setUsername(ctx.getStringAttribute(LdapIdentityLookup.this.identifierAttribute)); if (user.getDisplayName() == null) { user.setDisplayName(user.getFirstname() + ' ' + user.getLastname()); } return user; } };
/** * Obtains the authorities for the user who's directory entry is represented by the * supplied LdapUserDetails object. * * @param user the user who's authorities are required * @return the set of roles granted to the user. */ @Override public final Collection<GrantedAuthority> getGrantedAuthorities( DirContextOperations user, String username) { String userDn = user.getNameInNamespace(); if (logger.isDebugEnabled()) { logger.debug("Getting authorities for user " + userDn); } Set<GrantedAuthority> roles = getGroupMembershipRoles(userDn, username); Set<GrantedAuthority> extraRoles = getAdditionalRoles(user, username); if (extraRoles != null) { roles.addAll(extraRoles); } if (this.defaultRole != null) { roles.add(this.defaultRole); } List<GrantedAuthority> result = new ArrayList<>(roles.size()); result.addAll(roles); return result; }
@Override public UserDetails mapUserFromContext(DirContextOperations ctx, String username, Collection<? extends GrantedAuthority> authorities) { List<GrantedAuthority> mappedAuthorities = new ArrayList<>(); try { for (GrantedAuthority granted : authorities) { String mappedAuthority = environment.getProperty("role-mapper."+granted.getAuthority()); if (!StringUtils.isEmpty(mappedAuthority)) { mappedAuthorities.add(new SimpleGrantedAuthority(mappedAuthority)); } } } catch (Exception e){ LOGGER.error("Failed to load mapped authorities", e); } io.gravitee.management.idp.api.authentication.UserDetails userDetails = new io.gravitee.management.idp.api.authentication.UserDetails( username, "", mappedAuthorities); userDetails.setFirstname(ctx.getStringAttribute(LDAP_ATTRIBUTE_FIRSTNAME)); userDetails.setLastname(ctx.getStringAttribute(LDAP_ATTRIBUTE_LASTNAME)); userDetails.setEmail(ctx.getStringAttribute(LDAP_ATTRIBUTE_MAIL)); userDetails.setSource(LdapIdentityProvider.PROVIDER_TYPE); userDetails.setSourceId(ctx.getNameInNamespace()); return userDetails; }
protected GeoServerUser createUser(DirContextOperations dco) { GeoServerUser gsUser = new GeoServerUser(dco.getStringAttribute(userNameAttribute)); for (String attName : populatedAttributes) { try { Attribute att = dco.getAttributes().get(attName.toLowerCase()); if (att != null) { Object value = att.get(); if (value instanceof String) { gsUser.getProperties().put(attName, value); } } } catch (NamingException e) { LOGGER.log( Level.WARNING, "Could not populate value for user attribute " + attName, e); } } return gsUser; }
public LdapUser mapFromContext(DirContextOperations ctx) throws NamingException, UnsupportedMemberAffiliationException { Optional.ofNullable(ctx.getStringAttribute(identifierAttribute)).orElseThrow(() -> new InvalidSecurityConfigurationException( "Can not get a username using '" + identifierAttribute + "' attribute to identify the user.")); String username = ctx.getStringAttribute(identifierAttribute); Optional<String> firstName = Optional.ofNullable(ctx.getStringAttribute(firstNameAttribute)); Optional<String> lastName = Optional.ofNullable(ctx.getStringAttribute(lastNameAttribute)); Optional<String> email = Optional.ofNullable(ctx.getStringAttribute(mailAddressAttribute)); if (StringUtils.hasText(memberOfFilter)) { String[] memberOf = ctx.getStringAttributes(MEMBER_OF_ATTRIBUTE); if (!Arrays.asList(memberOf).contains(memberOfFilter)) { throw new UnsupportedMemberAffiliationException("User '" + username + "' is not a member of '" + memberOfFilter + "'"); } return new LdapUser(username, firstName, lastName, email, memberOf); } return new LdapUser(username, firstName, lastName, email); } }
@Override protected Object doMapFromContext(DirContextOperations ctx) { if (resultFilter != null && !resultFilter.needSelect(ctx.getNameInNamespace())){ return null; } Map<String, Object> result = new HashMap<>(); result.put(LdapConstant.LDAP_DN_KEY, ctx.getNameInNamespace()); List<Object> list = new ArrayList<>(); result.put("attributes", list); Attributes attributes = ctx.getAttributes(); NamingEnumeration it = attributes.getAll(); try { while (it.hasMore()){ list.add(it.next()); } } catch (javax.naming.NamingException e){ logger.error("query ldap entry attributes fail", e.getCause()); throw new OperationFailureException(operr("query ldap entry fail, %s", e.toString())); } return result; } }, processor);
@Test public void testRebindWithContext() throws Exception { expectGetReadWriteContext(); when(dirContextOperationsMock.getDn()).thenReturn(nameMock); when(dirContextOperationsMock.isUpdateMode()).thenReturn(false); tested.rebind(dirContextOperationsMock); verify(dirContextMock).rebind(nameMock, dirContextOperationsMock, null); verify(dirContextMock).close(); }
private void createRaveUserFromLdapInfo(DirContextOperations ctx, String username) { User newUser = new UserImpl(); newUser.setUsername(username); if (!ctx.attributeExists(mailAttributeName) || StringUtils.isBlank(ctx.getStringAttribute(mailAttributeName))) { throw new RuntimeException("Missing LDAP attribute for email for user " + username); } newUser.setEmail(ctx.getStringAttribute(mailAttributeName)); if (ctx.attributeExists(displayNameAttributeName)) { newUser.setDisplayName(ctx.getStringAttribute(displayNameAttributeName)); } newUser.setPassword(RandomStringUtils.random(16)); newUser.setDefaultPageLayoutCode(pageLayoutCode); try { newAccountService.createNewAccount(newUser); } catch (Exception e) { throw new RuntimeException("Could not bind LDAP username '{" + username + "}' to a user", e); } }
private String getPassword(DirContextOperations user) { Object passwordAttrValue = user.getObjectAttribute(this.passwordAttributeName); if (passwordAttrValue == null) { return null; } if (passwordAttrValue instanceof byte[]) { return new String((byte[]) passwordAttrValue); } return String.valueOf(passwordAttrValue); }
public DirContextOperations localCompareAuthenticate(DirContextOperations user, String password) { boolean match = false; try { Attributes attributes = user.getAttributes(); Attribute attr = attributes.get(getPasswordAttributeName()); if (attr.size()==0) { throw new AuthenticationCredentialsNotFoundException("Missing "+getPasswordAttributeName()+" attribute."); } for (int i = 0; (attr != null) && (!match) && (i < attr.size()); i++) { Object valObject = attr.get(i); if (valObject != null && valObject instanceof byte[]) { if (passwordEncoder instanceof DynamicPasswordComparator) { byte[] received = password.getBytes(); byte[] stored = (byte[]) valObject; match = ((DynamicPasswordComparator) passwordEncoder).comparePasswords(received, stored); } else { String encodedPassword = passwordEncoder.encodePassword(password, null); byte[] passwordBytes = Utf8.encode(encodedPassword); match = Arrays.equals(passwordBytes, (byte[]) valObject); } } } } catch (NamingException e) { throw new BadCredentialsException("Bad credentials", e); } if (!match) throw new BadCredentialsException("Bad credentials"); return user; }
@Test public void verifyCompleteReplacementOfUniqueMemberAttribute_Ldap119Workaround() { DirContextOperations ctx = tested.lookupContext("cn=ROLE_USER,ou=groups"); ctx.setAttributeValues("uniqueMember", new String[]{"cn=Some Person,ou=company1,ou=Norway," + base}, true); ctx.getModificationItems(); tested.modifyAttributes(ctx); }
@Override public Collection<GrantedAuthority> getGrantedAuthorities(DirContextOperations user, String username) { if (MEMBER_OF.equals(getGroupSearchBase())) { String[] memberOfs = user.getStringAttributes(MEMBER_OF); if (memberOfs==null || memberOfs.length==0) { return EMPTY_LIST; } else { return Arrays.stream(memberOfs).map(s -> new LdapAuthority(s,s)).collect(Collectors.toList()); } } else { return super.getGrantedAuthorities(user, username); } }