本文整理匯總了Java中org.springframework.ldap.core.DirContextOperations類的典型用法代碼示例。如果您正苦於以下問題:Java DirContextOperations類的具體用法?Java DirContextOperations怎麽用?Java DirContextOperations使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
DirContextOperations類屬於org.springframework.ldap.core包,在下文中一共展示了DirContextOperations類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: testJndiSpring
import org.springframework.ldap.core.DirContextOperations; //導入依賴的package包/類
@Test
public void testJndiSpring() throws Exception {
DefaultSpringSecurityContextSource ctxSrc = new DefaultSpringSecurityContextSource(
"ldap://ldap.xxx:389/OU=xxx");
ctxSrc.setUserDn(USER_LDAP);
ctxSrc.setPassword(PASSWORD_LDAP);
ctxSrc.afterPropertiesSet();
logger.info("Base LDAP Path: " + ctxSrc.getBaseLdapPath());
logger.info("Principal: "
+ ctxSrc.getAuthenticationSource().getPrincipal().toString());
logger.info("Credentials: "
+ ctxSrc.getAuthenticationSource().getCredentials());
Authentication bob = new UsernamePasswordAuthenticationToken("bob",
"bob");
BindAuthenticator authenticator = new BindAuthenticator(ctxSrc);
authenticator.setUserSearch(new FilterBasedLdapUserSearch("",
"(&(objectCategory=Person)(sAMAccountName={0}))", ctxSrc));
authenticator.afterPropertiesSet();
authenticator.authenticate(bob);
DirContextOperations user = authenticator.authenticate(bob);
logger.info("User: {}", user);
}
示例2: doMapFromContext
import org.springframework.ldap.core.DirContextOperations; //導入依賴的package包/類
@Override
public UserOrg doMapFromContext(final DirContextOperations context) {
final UserOrg user = new UserOrg();
user.setDn(context.getDn().toString());
user.setLastName(context.getStringAttribute("sn"));
user.setFirstName(context.getStringAttribute("givenName"));
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()));
// Save the mails
user.setMails(new ArrayList<>(CollectionUtils.emptyIfNull(context.getAttributeSortedStringSet("mail"))));
return user;
}
示例3: mapUserFromContext
import org.springframework.ldap.core.DirContextOperations; //導入依賴的package包/類
public UserDetails mapUserFromContext(DirContextOperations ctx, String username,
Collection<? extends GrantedAuthority> authorities) {
String dn = ctx.getNameInNamespace();
logger.debug("Mapping user details from context with DN: " + dn);
// User must be defined in Airsonic, unless auto-shadowing is enabled.
User user = securityService.getUserByName(username, false);
if (user == null && !settingsService.isLdapAutoShadowing()) {
throw new BadCredentialsException("User does not exist.");
}
if (user == null) {
User newUser = new User(username, "", null, true, 0L, 0L, 0L);
newUser.setStreamRole(true);
newUser.setSettingsRole(true);
securityService.createUser(newUser);
logger.info("Created local user '" + username + "' for DN " + dn);
user = securityService.getUserByName(username, false);
}
// LDAP authentication must be enabled for the given user.
if (!user.isLdapAuthenticated()) {
throw new BadCredentialsException("LDAP authentication disabled for user.");
}
LdapUserDetailsImpl.Essence essence = new LdapUserDetailsImpl.Essence();
essence.setDn(dn);
Object passwordValue = ctx.getObjectAttribute(passwordAttributeName);
if (passwordValue != null) {
essence.setPassword(mapPassword(passwordValue));
}
essence.setUsername(user.getUsername());
// Add the supplied authorities
for (GrantedAuthority authority : securityService.getGrantedAuthorities(user.getUsername())) {
essence.addAuthority(authority);
}
// Check for PPolicy data
PasswordPolicyResponseControl ppolicy = (PasswordPolicyResponseControl) ctx
.getObjectAttribute(PasswordPolicyControl.OID);
if (ppolicy != null) {
essence.setTimeBeforeExpiration(ppolicy.getTimeBeforeExpiration());
essence.setGraceLoginsRemaining(ppolicy.getGraceLoginsRemaining());
}
return essence.createUserDetails();
}
示例4: searchForUser
import org.springframework.ldap.core.DirContextOperations; //導入依賴的package包/類
/**
* Return the DirContextOperations containing the user's information
*
* @param dn full DN of the user to search for.
*
* @return An DirContextOperations object containing the details of the located user's
* directory entry
*
* @throws UsernameNotFoundException if no matching entry is found.
*/
@Override
public DirContextOperations searchForUser(String dn) {
log.debug("Searching for dn '{}'.", dn);
SpringSecurityLdapTemplate template = new SpringSecurityLdapTemplate(getContextSource());
template.setSearchControls(getSearchControls());
try {
return template.retrieveEntry(dn, null);
} catch (IncorrectResultSizeDataAccessException ex) {
if (ex.getActualSize() == 0) {
throw new UsernameNotFoundException("User " + dn + " not found in directory.");
}
// Search should never return multiple results if properly configured, so just rethrow
throw ex;
}
}
示例5: getGrantedAuthorities
import org.springframework.ldap.core.DirContextOperations; //導入依賴的package包/類
@Override
public Collection<? extends GrantedAuthority> getGrantedAuthorities(DirContextOperations userData, String username) {
Collection<? extends GrantedAuthority> authorities = delegate.getGrantedAuthorities(userData, username);
if (authorities != null) {
return authorities.stream()
.map(GrantedAuthority::getAuthority)
.map(a -> authorityToPermissionMap.get(a))
.filter(Objects::nonNull)
.filter(a -> !a.isEmpty())
.map(SimpleGrantedAuthority::new)
.collect(Collectors.toSet());
} else {
return null;
}
}
示例6: uid2ext
import org.springframework.ldap.core.DirContextOperations; //導入依賴的package包/類
public String uid2ext(String uid) {
String externalIdAttribute = ApplicationProperty.AuthenticationLdapIdAttribute.value();
if ("uid".equals(externalIdAttribute)) return uid; // Nothing to translate
try {
ContextSource source = (ContextSource)SpringApplicationContextHolder.getBean("unitimeLdapContextSource");
String query = ApplicationProperty.AuthenticationLdapLogin2UserId.value();
SpringSecurityLdapTemplate template = new SpringSecurityLdapTemplate(source);
DirContextOperations user = template.retrieveEntry(query.replaceAll("\\{0\\}", uid), new String[] {externalIdAttribute});
return user == null ? null : user.getStringAttribute(externalIdAttribute);
} catch (Exception e) {
sLog.warn("Unable to translate uid to " + externalIdAttribute + ": " + e.getMessage());
}
return null;
}
示例7: ext2uid
import org.springframework.ldap.core.DirContextOperations; //導入依賴的package包/類
public String ext2uid(String externalUserId) {
String externalIdAttribute = ApplicationProperty.AuthenticationLdapIdAttribute.value();
if ("uid".equals(externalIdAttribute)) return externalUserId; // Nothing to translate
try {
ContextSource source = (ContextSource)SpringApplicationContextHolder.getBean("unitimeLdapContextSource");
String query = ApplicationProperty.AuthenticationLdapUserId2Login.value().replace("%", externalIdAttribute);
SpringSecurityLdapTemplate template = new SpringSecurityLdapTemplate(source);
DirContextOperations user = template.retrieveEntry(query.replaceAll("\\{0\\}", externalIdAttribute), new String[] {"uid"});
return user == null ? null : user.getStringAttribute("uid");
} catch (Exception e) {
sLog.warn("Unable to translate " + externalIdAttribute + " to uid: " + e.getMessage());
}
return null;
}
示例8: getUserIdentity
import org.springframework.ldap.core.DirContextOperations; //導入依賴的package包/類
private String getUserIdentity(final DirContextOperations ctx) {
final String identity;
if (useDnForUserIdentity) {
identity = ctx.getDn().toString();
} else {
final Attribute attributeName = ctx.getAttributes().get(userIdentityAttribute);
if (attributeName == null) {
throw new AuthorizationAccessException("User identity attribute [" + userIdentityAttribute + "] does not exist.");
}
try {
identity = (String) attributeName.get();
} catch (NamingException e) {
throw new AuthorizationAccessException("Error while retrieving user name attribute [" + userIdentityAttribute + "].");
}
}
return IdentityMappingUtil.mapIdentity(identity, identityMappings);
}
示例9: getReferencedUserValue
import org.springframework.ldap.core.DirContextOperations; //導入依賴的package包/類
private String getReferencedUserValue(final DirContextOperations ctx) {
final String referencedUserValue;
if (StringUtils.isBlank(groupMemberReferencedUserAttribute)) {
referencedUserValue = ctx.getDn().toString();
} else {
final Attribute attributeName = ctx.getAttributes().get(groupMemberReferencedUserAttribute);
if (attributeName == null) {
throw new AuthorizationAccessException("Referenced user value attribute [" + groupMemberReferencedUserAttribute + "] does not exist.");
}
try {
referencedUserValue = (String) attributeName.get();
} catch (NamingException e) {
throw new AuthorizationAccessException("Error while retrieving reference user value attribute [" + groupMemberReferencedUserAttribute + "].");
}
}
return referencedUserValue;
}
示例10: getGroupName
import org.springframework.ldap.core.DirContextOperations; //導入依賴的package包/類
private String getGroupName(final DirContextOperations ctx) {
final String name;
if (useDnForGroupName) {
name = ctx.getDn().toString();
} else {
final Attribute attributeName = ctx.getAttributes().get(groupNameAttribute);
if (attributeName == null) {
throw new AuthorizationAccessException("Group identity attribute [" + groupNameAttribute + "] does not exist.");
}
try {
name = (String) attributeName.get();
} catch (NamingException e) {
throw new AuthorizationAccessException("Error while retrieving group name attribute [" + groupNameAttribute + "].");
}
}
return name;
}
示例11: getReferencedGroupValue
import org.springframework.ldap.core.DirContextOperations; //導入依賴的package包/類
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;
}
示例12: createUser
import org.springframework.ldap.core.DirContextOperations; //導入依賴的package包/類
private User createUser(DirContextOperations authenticate) {
DefaultUser user = new DefaultUser(authenticate.getStringAttribute(identifierAttribute));
// add additional information
Map<String, Object> claims = new HashMap<>();
if (mapper.getMappers() != null) {
mapper.getMappers().forEach((k, v) -> {
claims.put(k, authenticate.getStringAttribute(v));
});
} else {
// default values
claims.put("sub", authenticate.getStringAttribute("uid"));
claims.put("email", authenticate.getStringAttribute("mail"));
claims.put("name", authenticate.getStringAttribute("displayname"));
claims.put("given_name", authenticate.getStringAttribute("givenname"));
claims.put("family_name", authenticate.getStringAttribute("sn"));
}
user.setAdditonalInformation(claims);
// set user roles
user.setRoles(getUserRoles(authenticate));
return user;
}
示例13: doAuthentication
import org.springframework.ldap.core.DirContextOperations; //導入依賴的package包/類
@Override
protected DirContextOperations doAuthentication(
UsernamePasswordAuthenticationToken auth) {
String username = auth.getName();
String password = (String) auth.getCredentials();
DirContext ctx = bindAsUser(username, password);
try {
return searchForUser(ctx, username);
}
catch (NamingException e) {
logger.error("Failed to locate directory entry for authenticated user: "
+ username, e);
throw badCredentials(e);
}
finally {
LdapUtils.closeContext(ctx);
}
}
示例14: loadUserAuthorities
import org.springframework.ldap.core.DirContextOperations; //導入依賴的package包/類
/**
* Creates the user authority list from the values of the {@code memberOf} attribute
* obtained from the user's Active Directory entry.
*/
@Override
protected Collection<? extends GrantedAuthority> loadUserAuthorities(
DirContextOperations userData, String username, String password) {
String[] groups = userData.getStringAttributes("memberOf");
if (groups == null) {
logger.debug("No values for 'memberOf' attribute.");
return AuthorityUtils.NO_AUTHORITIES;
}
if (logger.isDebugEnabled()) {
logger.debug("'memberOf' attribute values: " + Arrays.asList(groups));
}
ArrayList<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(
groups.length);
for (String group : groups) {
authorities.add(new SimpleGrantedAuthority(new DistinguishedName(group).removeLast().getValue()));
}
return authorities;
}
示例15: searchForUser
import org.springframework.ldap.core.DirContextOperations; //導入依賴的package包/類
private DirContextOperations searchForUser(DirContext context, String username)
throws NamingException {
SearchControls searchControls = new SearchControls();
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
String bindPrincipal = createBindPrincipalDomainAlias(username);
String searchRoot = rootDn != null ? rootDn : searchRootFromPrincipal(bindPrincipal);
try {
return SpringSecurityLdapTemplate.searchForSingleEntryInternal(context,
searchControls, searchRoot, searchFilter,
new Object[] { bindPrincipal });
}
catch (IncorrectResultSizeDataAccessException incorrectResults) {
// Search should never return multiple results if properly configured - just
// rethrow
if (incorrectResults.getActualSize() != 0) {
throw incorrectResults;
}
// If we found no results, then the username/password did not match
UsernameNotFoundException userNameNotFoundException = new UsernameNotFoundException(
"User " + username + " not found in directory.", incorrectResults);
throw badCredentials(userNameNotFoundException);
}
}