List of usage examples for javax.naming.directory SearchResult getNameInNamespace
public String getNameInNamespace()
From source file:org.nuxeo.wizard.RouterServlet.java
public void handleUserPOST(Page currentPage, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Context ctx = Context.instance(req); ParamCollector collector = ctx.getCollector(); String refreshParam = req.getParameter("refresh"); String directoryType = collector.getConfigurationParam("nuxeo.directory.type"); if ("true".equals(refreshParam)) { currentPage.dispatchToJSP(req, resp); return;/*from ww w . j a v a 2 s . c o m*/ } if ("checkNetwork".equals(refreshParam) || "checkAuth".equals(refreshParam) || "checkUserLdapParam".equals(refreshParam) || "checkGroupLdapParam".equals(refreshParam)) { try { if ("checkNetwork".equals(refreshParam)) { bindLdapConnection(collector, false); ctx.trackInfo("nuxeo.ldap.url", "info.host.found"); } else if ("checkAuth".equals(refreshParam)) { bindLdapConnection(collector, true); ctx.trackInfo("nuxeo.ldap.auth", "info.auth.success"); } else { DirContext dirContext = new InitialDirContext(getContextEnv(collector, true)); String searchScope; String searchBaseDn; String searchClass; String searchFilter; if ("checkUserLdapParam".equals(refreshParam)) { searchBaseDn = collector.getConfigurationParam("nuxeo.ldap.user.searchBaseDn"); searchScope = collector.getConfigurationParam("nuxeo.ldap.user.searchScope"); searchClass = collector.getConfigurationParam("nuxeo.ldap.user.searchClass"); searchFilter = collector.getConfigurationParam("nuxeo.ldap.user.searchFilter"); } else { searchBaseDn = collector.getConfigurationParam("nuxeo.ldap.group.searchBaseDn"); searchScope = collector.getConfigurationParam("nuxeo.ldap.group.searchScope"); searchFilter = collector.getConfigurationParam("nuxeo.ldap.group.searchFilter"); searchClass = ""; } SearchControls scts = new SearchControls(); if ("onelevel".equals(searchScope)) { scts.setSearchScope(SearchControls.ONELEVEL_SCOPE); } else { scts.setSearchScope(SearchControls.SUBTREE_SCOPE); } String filter = String.format("(&(%s)(objectClass=%s))", searchFilter.isEmpty() ? "objectClass=*" : searchFilter, searchClass.isEmpty() ? "*" : searchClass); NamingEnumeration<SearchResult> results; try { results = dirContext.search(searchBaseDn, filter, scts); if (!results.hasMore()) { ctx.trackError("nuxeo.ldap.search", "error.ldap.noresult"); } else { SearchResult result = results.next(); if (searchBaseDn.equalsIgnoreCase(result.getNameInNamespace()) && results.hasMore()) { // try not to display the root of the search // base DN result = results.next(); } ctx.trackInfo("dn", result.getNameInNamespace()); Attributes attributes = result.getAttributes(); NamingEnumeration<String> ids = attributes.getIDs(); String id; StringBuilder sb; while (ids.hasMore()) { id = ids.next(); NamingEnumeration<?> values = attributes.get(id).getAll(); sb = new StringBuilder(); while (values.hasMore()) { sb.append(values.next()).append(" , "); } ctx.trackInfo(id, sb.substring(0, sb.length() - 3)); } } } catch (NameNotFoundException e) { ctx.trackError("nuxeo.ldap.search", "error.ldap.searchBaseDn"); log.warn(e); } dirContext.close(); } } catch (AuthenticationException e) { ctx.trackError("nuxeo.ldap.auth", "error.auth.failed"); log.warn(e); } catch (NamingException e) { ctx.trackError("nuxeo.ldap.url", "error.host.not.found"); log.warn(e); } } // Form submit if (!"default".equals(directoryType) && refreshParam.isEmpty()) { // first check bind to LDAP server try { bindLdapConnection(collector, true); } catch (NamingException e) { ctx.trackError("nuxeo.ldap.auth", "error.ldap.bind.failed"); log.warn(e); } // then check mandatory fields if (collector.getConfigurationParam("nuxeo.ldap.user.searchBaseDn").isEmpty()) { ctx.trackError("nuxeo.ldap.user.searchBaseDn", "error.user.searchBaseDn.required"); } if (collector.getConfigurationParam("nuxeo.ldap.user.mapping.rdn").isEmpty()) { ctx.trackError("nuxeo.ldap.user.mapping.rdn", "error.user.rdn.required"); } if (collector.getConfigurationParam("nuxeo.ldap.user.mapping.username").isEmpty()) { ctx.trackError("nuxeo.ldap.user.mapping.username", "error.user.username.required"); } if (collector.getConfigurationParam("nuxeo.ldap.user.mapping.password").isEmpty()) { ctx.trackError("nuxeo.ldap.user.mapping.password", "error.user.password.required"); } if (collector.getConfigurationParam("nuxeo.ldap.user.mapping.firstname").isEmpty()) { ctx.trackError("nuxeo.ldap.user.mapping.firstname", "error.user.firstname.required"); } if (collector.getConfigurationParam("nuxeo.ldap.user.mapping.lastname").isEmpty()) { ctx.trackError("nuxeo.ldap.user.mapping.lastname", "error.user.lastname.required"); } String userGroupStorage = collector.getConfigurationParam("nuxeo.user.group.storage"); if (!"userLdapOnly".equals(userGroupStorage) && !"multiUserSqlGroup".equals(userGroupStorage)) { if (collector.getConfigurationParam("nuxeo.ldap.group.searchBaseDn").isEmpty()) { ctx.trackError("nuxeo.ldap.group.searchBaseDn", "error.group.searchBaseDn.required"); } if (collector.getConfigurationParam("nuxeo.ldap.group.mapping.rdn").isEmpty()) { ctx.trackError("nuxeo.ldap.group.mapping.rdn", "error.group.rdn.required"); } if (collector.getConfigurationParam("nuxeo.ldap.group.mapping.name").isEmpty()) { ctx.trackError("nuxeo.ldap.group.mapping.name", "error.group.name.required"); } } if ("true".equals(collector.getConfigurationParam("nuxeo.user.emergency.enable"))) { if (collector.getConfigurationParam("nuxeo.user.emergency.username").isEmpty()) { ctx.trackError("nuxeo.user.emergency.username", "error.emergency.username.required"); } if (collector.getConfigurationParam("nuxeo.user.emergency.password").isEmpty()) { ctx.trackError("nuxeo.user.emergency.password", "error.emergency.password.required"); } } } if (ctx.hasErrors() || ctx.hasInfos()) { currentPage.dispatchToJSP(req, resp); } else { currentPage.next().dispatchToJSP(req, resp, true); } }
From source file:com.funambol.LDAP.security.LDAPUserProvisioningOfficer.java
/** * Return a S4J user if successful bind to ldap * null if user or password is wrong/* w w w . java2 s.com*/ * * TODO if I don't need to provision user on ldap, I could avoid some of that stuff.. * when binding, it retrieves imap/smtp server data to provision mail push * @param username * @param password * @return the {@link Sync4jUser} created from ldap fields */ public LDAPUser bindUserToLdap(String username, String password) { LDAPUser ldapUser = null; String userDN = null; LdapManagerInterface ldapBindInterface = null; /* TODO * this is now done creating an eventually authenticated context specified in * configuration file. * moreover this context is shared between all ldap connections, * so could be better defined at application server level */ try { TempParams t = new TempParams(); // if username is an email substitute %u e %d in baseDn: expandSearchAndBaseDn(username, t); // setup the default LdapInterface configured with bean data // use a bean configuration file ldapInterface = LDAPManagerFactory.createLdapInterface(getLdapInterfaceClassName()); ldapInterface.init(t.tmpLdapUrl, t.tmpBaseDn, getSearchBindDn(), getSearchBindPassword(), isFollowReferral(), isConnectionPooling(), null); // set the userDN when custom user search if (!StringUtils.isEmpty(getUserSearch())) { // search the user binding with default ldap credential defined in the Officer.xml ldapInterface.setBaseDn(t.tmpBaseDn); SearchResult sr = ldapInterface.searchOneEntry(t.tmpUserSearch, new String[] { "dn" }, SearchControls.SUBTREE_SCOPE); if (sr != null) { userDN = sr.getNameInNamespace().trim(); log.info("binding with dn:" + userDN); } else { log.info("Username" + username + "not found"); return null; } } else { // use append userDN = "uid=" + username + "," + baseDn; } ldapInterface.close(); ldapBindInterface = LDAPManagerFactory.createLdapInterface(getLdapInterfaceClassName()); ldapBindInterface.init(t.tmpLdapUrl, userDN, userDN, password, false, false, null); SearchResult sr = ldapBindInterface.searchOneEntry("(objectclass=*)", getLdapAttributesToRetrieve(), SearchControls.OBJECT_SCOPE); if (sr != null) { ldapUser = new LDAPUser(); ldapUser.setUsername(username); ldapUser.setPassword(password); if (StringUtils.isNotEmpty(getAttributeMap().get(Constants.USER_EMAIL))) { ldapUser.setEmail( LdapUtils.getPrettyAttribute(sr, getAttributeMap().get(Constants.USER_EMAIL))); } if (StringUtils.isNotEmpty(getAttributeMap().get(Constants.USER_FIRSTNAME))) { ldapUser.setFirstname( LdapUtils.getPrettyAttribute(sr, getAttributeMap().get(Constants.USER_FIRSTNAME))); } if (StringUtils.isNotEmpty(getAttributeMap().get(Constants.USER_LASTNAME))) { ldapUser.setLastname( LdapUtils.getPrettyAttribute(sr, getAttributeMap().get(Constants.USER_LASTNAME))); } // set attributes to be passed to LDAP and CalDAV connector ldapUser.setUserDn(userDN); if (StringUtils.isNotEmpty(getAttributeMap().get(Constants.USER_ADDRESSBOOK))) { ldapUser.setPsRoot( LdapUtils.getPrettyAttribute(sr, getAttributeMap().get(Constants.USER_ADDRESSBOOK))); } if (StringUtils.isNotEmpty(getAttributeMap().get(Constants.USER_CALENDAR))) { ldapUser.setPsRoot( LdapUtils.getPrettyAttribute(sr, getAttributeMap().get(Constants.USER_CALENDAR))); } } else { return null; } } catch (SyncSourceException e1) { log.error("Can't instantiate context: " + e1.getMessage()); ldapUser = null; } catch (NamingException e) { log.warn("Can't retrieve mailserver attributes from ldap: " + e.getMessage()); ldapUser = null; } catch (LDAPAccessException e) { log.error("Can't instantiate context: " + e.getMessage()); ldapUser = null; } finally { if (ldapInterface != null) { ldapInterface.close(); } if (ldapBindInterface != null) { ldapBindInterface.close(); } } return ldapUser; }
From source file:org.apache.zeppelin.realm.LdapRealm.java
/** * Returns the LDAP User Distinguished Name (DN) to use when acquiring an * {@link javax.naming.ldap.LdapContext LdapContext} from the * {@link LdapContextFactory}./* w ww.ja va 2s . c om*/ * <p/> * If the the {@link #getUserDnTemplate() userDnTemplate} property has been * set, this implementation will construct the User DN by substituting the * specified {@code principal} into the configured template. If the * {@link #getUserDnTemplate() userDnTemplate} has not been set, the method * argument will be returned directly (indicating that the submitted * authentication token principal <em>is</em> the User DN). * * @param principal * the principal to substitute into the configured * {@link #getUserDnTemplate() userDnTemplate}. * @return the constructed User DN to use at runtime when acquiring an * {@link javax.naming.ldap.LdapContext}. * @throws IllegalArgumentException * if the method argument is null or empty * @throws IllegalStateException * if the {@link #getUserDnTemplate userDnTemplate} has not been * set. * @see LdapContextFactory#getLdapContext(Object, Object) */ @Override protected String getUserDn(final String principal) throws IllegalArgumentException, IllegalStateException { String userDn; String matchedPrincipal = matchPrincipal(principal); String userSearchBase = getUserSearchBase(); String userSearchAttributeName = getUserSearchAttributeName(); // If not searching use the userDnTemplate and return. if ((userSearchBase == null || userSearchBase.isEmpty()) || (userSearchAttributeName == null && userSearchFilter == null && !"object".equalsIgnoreCase(userSearchScope))) { userDn = expandTemplate(userDnTemplate, matchedPrincipal); if (log.isDebugEnabled()) { log.debug("LDAP UserDN and Principal: " + userDn + "," + principal); } return userDn; } // Create the searchBase and searchFilter from config. String searchBase = expandTemplate(getUserSearchBase(), matchedPrincipal); String searchFilter = null; if (userSearchFilter == null) { if (userSearchAttributeName == null) { searchFilter = String.format("(objectclass=%1$s)", getUserObjectClass()); } else { searchFilter = String.format("(&(objectclass=%1$s)(%2$s=%3$s))", getUserObjectClass(), userSearchAttributeName, expandTemplate(getUserSearchAttributeTemplate(), matchedPrincipal)); } } else { searchFilter = expandTemplate(userSearchFilter, matchedPrincipal); } SearchControls searchControls = getUserSearchControls(); // Search for userDn and return. LdapContext systemLdapCtx = null; NamingEnumeration<SearchResult> searchResultEnum = null; try { systemLdapCtx = getContextFactory().getSystemLdapContext(); if (log.isDebugEnabled()) { log.debug("SearchBase,SearchFilter,UserSearchScope: " + searchBase + "," + searchFilter + "," + userSearchScope); } searchResultEnum = systemLdapCtx.search(searchBase, searchFilter, searchControls); // SearchResults contains all the entries in search scope if (searchResultEnum.hasMore()) { SearchResult searchResult = searchResultEnum.next(); userDn = searchResult.getNameInNamespace(); if (log.isDebugEnabled()) { log.debug("UserDN Returned,Principal: " + userDn + "," + principal); } return userDn; } else { throw new IllegalArgumentException("Illegal principal name: " + principal); } } catch (AuthenticationException ne) { ne.printStackTrace(); throw new IllegalArgumentException("Illegal principal name: " + principal); } catch (NamingException ne) { throw new IllegalArgumentException("Hit NamingException: " + ne.getMessage()); } finally { try { if (searchResultEnum != null) { searchResultEnum.close(); } } catch (NamingException ne) { // Ignore exception on close. } finally { LdapUtils.closeContext(systemLdapCtx); } } }
From source file:org.olat.ldap.LDAPLoginManagerImpl.java
/** * Find the user dn with its uid// w w w.j a v a 2s.com * * @param uid * @param ctx * @return user's dn */ private String searchUserDN(final String uid, final DirContext ctx) { if (ctx == null) { return null; } final List<String> ldapBases = LDAPLoginModule.getLdapBases(); final String objctClass = LDAPLoginModule.getLdapUserObjectClass(); final String[] serachAttr = { "dn" }; final String ldapUserIDAttribute = LDAPLoginModule .mapOlatPropertyToLdapAttribute(LDAPConstants.LDAP_USER_IDENTIFYER); final String filter = "(&(objectClass=" + objctClass + ")(" + ldapUserIDAttribute + "=" + uid + "))"; final SearchControls ctls = new SearchControls(); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); ctls.setReturningAttributes(serachAttr); String userDN = null; for (final String ldapBase : ldapBases) { try { final NamingEnumeration<SearchResult> enm = ctx.search(ldapBase, filter, ctls); while (enm.hasMore()) { final SearchResult result = enm.next(); userDN = result.getNameInNamespace(); } if (userDN != null) { break; } } catch (final NamingException e) { logError("NamingException when trying to bind user with username::" + uid + " on ldapBase::" + ldapBase, e); } } return userDN; }
From source file:com.funambol.LDAP.security.LDAPUserProvisioningOfficer.java
/** * return false if user or password is wrong * // ww w. j ava2 s.c om * here we expand attributes: %u, %d, %s * if defined userSearch, retrieve user's DN and try to bind with it * @param username * @param password * @return */ private boolean ldapBind(String username, String password) { String userDN = null; try { TempParams t = new TempParams(); // if username is an email substitute %u e %d in baseDn: expandSearchAndBaseDn(username, t); // setup the default LdapInterface configured with bean data ldapInterface = LDAPManagerFactory.createLdapInterface(getLdapInterfaceClassName()); ldapInterface.init(getLdapUrl(), getBaseDn(), getSearchBindDn(), getSearchBindPassword(), isFollowReferral(), isConnectionPooling(), null); // set the userDN when custom user search if (!StringUtils.isEmpty(getUserSearch())) { // customize the field used to search the user. SearchResult sr = ldapInterface.searchOneEntry(getUserSearch(), new String[] { "dn" }, SearchControls.SUBTREE_SCOPE); if (sr == null) { log.info("Username " + username + " not found"); return false; } userDN = sr.getNameInNamespace().trim(); log.info("binding with dn:" + userDN); } // on failure, set the user DN with append if (userDN == null) { userDN = "uid=" + username + "," + baseDn; } } catch (Exception e) { log.error("Can't instantiate LdapInterface: " + e.getMessage()); return false; } // Set up environment for creating initial context Hashtable<String, String> env = new Hashtable<String, String>(11); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, getLdapUrl()); // Authenticate as User and password env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_PRINCIPAL, userDN); env.put(Context.SECURITY_CREDENTIALS, password); try { DirContext ctx = new InitialDirContext(env); log.debug(ctx.lookup(userDN)); ctx.close(); } catch (AuthenticationException e) { log.info("User not authenticated: " + e.getMessage()); return false; } catch (NamingException e) { log.warn("User not authenticated: problem while accessing ldap " + e.getMessage()); e.printStackTrace(); return false; } return true; }
From source file:org.swordess.ldap.odm.core.SessionImpl.java
@Override public <T> List<T> search(Class<T> clazz, String filter) { if (null == filter) { return null; }/*from w w w . j a v a 2s . c om*/ LogUtils.debug(LOG, "search " + clazz.getName() + " with filter=" + filter); SearchControls ctrl = new SearchControls(); ctrl.setSearchScope(SearchControls.SUBTREE_SCOPE); ctrl.setReturningAttributes(EntityMetaData.getDefinedAttrNames(clazz)); List<T> retVal = new ArrayList<T>(); try { NamingEnumeration<SearchResult> results = ctx.search(EntityMetaData.get(clazz).context(), filter, ctrl); while (results.hasMore()) { try { SearchResult result = results.next(); T entity = null; if (sessionCache.containsKey(result.getNameInNamespace())) { // guarantee the reference integrity for one search result entity = (T) sessionCache.get(result.getNameInNamespace()); } else { entity = fromAttributesToEntity(clazz, result.getAttributes()); sessionCache.put(result.getNameInNamespace(), entity); } retVal.add(entity); } catch (NamingException e) { LogUtils.error(LOG, "Unable to construct the entity", e); } } } catch (NamingException e) { throw new SessionException(e.getMessage(), e); } return retVal; }
From source file:org.nuxeo.ecm.directory.ldap.LDAPSession.java
protected SearchResult getLdapEntry(String id, boolean fetchAllAttributes) throws NamingException { if (StringUtils.isEmpty(id)) { log.warn(/* w ww. j a va 2 s . c o m*/ "The application should not " + "query for entries with an empty id " + "=> return no results"); return null; } String filterExpr; String baseFilter = getDirectory().getBaseFilter(); if (baseFilter.startsWith("(")) { filterExpr = String.format("(&(%s={0})%s)", idAttribute, baseFilter); } else { filterExpr = String.format("(&(%s={0})(%s))", idAttribute, baseFilter); } String[] filterArgs = { id }; SearchControls scts = getDirectory().getSearchControls(fetchAllAttributes); if (log.isDebugEnabled()) { log.debug(String.format( "LDAPSession.getLdapEntry(%s, %s): LDAP search base='%s' filter='%s' " + " args='%s' scope='%s' [%s]", id, fetchAllAttributes, searchBaseDn, filterExpr, id, scts.getSearchScope(), this)); } NamingEnumeration<SearchResult> results; try { results = dirContext.search(searchBaseDn, filterExpr, filterArgs, scts); } catch (NameNotFoundException nnfe) { // sometimes ActiveDirectory have some query fail with: LDAP: // error code 32 - 0000208D: NameErr: DSID-031522C9, problem // 2001 (NO_OBJECT). // To keep the application usable return no results instead of // crashing but log the error so that the AD admin // can fix the issue. log.error("Unexpected response from server while performing query: " + nnfe.getMessage(), nnfe); return null; } if (!results.hasMore()) { log.debug("Entry not found: " + id); return null; } SearchResult result = results.next(); try { String dn = result.getNameInNamespace(); if (results.hasMore()) { result = results.next(); String dn2 = result.getNameInNamespace(); String msg = String.format("Unable to fetch entry for '%s': found more than one match," + " for instance: '%s' and '%s'", id, dn, dn2); log.error(msg); // ignore entries that are ambiguous while giving enough info // in the logs to let the LDAP admin be able to fix the issue return null; } if (log.isDebugEnabled()) { log.debug(String.format( "LDAPSession.getLdapEntry(%s, %s): LDAP search base='%s' filter='%s' " + " args='%s' scope='%s' => found: %s [%s]", id, fetchAllAttributes, searchBaseDn, filterExpr, id, scts.getSearchScope(), dn, this)); } } catch (UnsupportedOperationException e) { // ignore unsupported operation thrown by the Apache DS server in // the tests in embedded mode } return result; }
From source file:net.identio.server.service.authentication.ldap.LdapAuthenticationProvider.java
public AuthenticationResult validate(AuthMethod authMethod, Authentication authentication, TransactionData transactionData) { LdapAuthMethod ldapAuthMethod = (LdapAuthMethod) authMethod; UserPasswordAuthentication userPwAuthentication = (UserPasswordAuthentication) authentication; boolean validation; String userId = userPwAuthentication.getUserId(); String password = userPwAuthentication.getPassword(); GenericObjectPool<InitialLdapContext> pool = pools.get(authMethod.getName()); InitialLdapContext ctx = null; try {/*from w w w .ja va 2 s . c om*/ ctx = pool.borrowObject(); // First we search the user SearchControls controls = new SearchControls(); controls.setSearchScope(SearchControls.SUBTREE_SCOPE); String searchFilter = ldapAuthMethod.getUserSearchFilter().replace("#UID", SecurityUtils.escapeLDAPSearchFilter(userId)); NamingEnumeration<SearchResult> results = ctx.search(ldapAuthMethod.getBaseDn(), searchFilter, controls); SearchResult result; if (results.hasMoreElements()) { result = results.next(); if (results.hasMoreElements()) { LOG.error("User ID {} is not unique in LDAP {}", userId, authMethod.getName()); return new AuthenticationResult().setStatus(AuthenticationResultStatus.FAIL) .setErrorStatus(AuthenticationErrorStatus.USER_NOT_UNIQUE); } } else { LOG.error("User ID {} does not exist in LDAP {}", userId, authMethod.getName()); return new AuthenticationResult().setStatus(AuthenticationResultStatus.FAIL) .setErrorStatus(AuthenticationErrorStatus.INVALID_CREDENTIALS); } // Try to bind with the found user id validation = ((LdapConnectionFactory) pool.getFactory()).authenticate(authMethod.getName(), result.getNameInNamespace(), password); pool.returnObject(ctx); if (validation) { LOG.info("User {} successfully authenticated with {}", userId, authMethod.getName()); return new AuthenticationResult().setStatus(AuthenticationResultStatus.SUCCESS).setUserId(userId) .setAuthMethod(authMethod).setAuthLevel(authMethod.getAuthLevel()); } else { LOG.error("Authentication failed for user {} with {}", userId, authMethod.getName()); return new AuthenticationResult().setStatus(AuthenticationResultStatus.FAIL) .setErrorStatus(AuthenticationErrorStatus.INVALID_CREDENTIALS); } } catch (Exception ex) { // Discard context try { if (ctx != null) { pool.invalidateObject(ctx); } } catch (Exception ex2) { LOG.error("An error occurend when authenticating user"); } return new AuthenticationResult().setStatus(AuthenticationResultStatus.FAIL) .setErrorStatus(AuthenticationErrorStatus.TECHNICAL_ERROR); } }
From source file:com.dtolabs.rundeck.jetty.jaas.JettyCachingLdapLoginModule.java
/** * binding authentication check This methode of authentication works only if * the user branch of the DIT (ldap tree) has an ACI (acces control * instruction) that allow the access to any user or at least for the user * that logs in./*from ww w. java2 s . c om*/ * * @param username * @param password * @return * @throws LoginException */ @SuppressWarnings("unchecked") protected boolean bindingLogin(String username, Object password) throws LoginException, NamingException { final String cacheToken = Credential.MD5.digest(username + ":" + password.toString()); if (_cacheDuration > 0) { // only worry about caching if there is a cacheDuration set. CachedUserInfo cached = USERINFOCACHE.get(cacheToken); if (cached != null) { if (System.currentTimeMillis() < cached.expires) { debug("Cache Hit for " + username + "."); userInfoCacheHits++; JAASUserInfo jaasUserInfo = new JAASUserInfo(cached.userInfo); try { jaasUserInfo.fetchRoles(); } catch (Exception ex) { if (_debug) { LOG.debug("Failed to fetch roles", ex); } throw new LoginException("Error obtaining user info."); } setCurrentUser(jaasUserInfo); setAuthenticated(true); return true; } else { LOG.info("Cache Eviction for " + username + "."); USERINFOCACHE.remove(cacheToken); } } else { debug("Cache Miss for " + username + "."); } } SearchResult searchResult = findUser(username); String userDn = searchResult.getNameInNamespace(); LOG.info("Attempting authentication: " + userDn); DirContext dirContext = createBindUserDirContext(userDn, password); setDemographicAttributes(searchResult.getAttributes()); // use _rootContext to find roles, if configured to doso if (_forceBindingLoginUseRootContextForRoles) { dirContext = _rootContext; debug("Using _rootContext for role lookup."); } List roles = getUserRolesByDn(dirContext, userDn, username); UserInfo userInfo = new UserInfo(username, new Password(password.toString()), roles); if (_cacheDuration > 0) { USERINFOCACHE.put(cacheToken, new CachedUserInfo(userInfo, System.currentTimeMillis() + _cacheDuration)); debug("Adding " + username + " set to expire: " + System.currentTimeMillis() + _cacheDuration); } JAASUserInfo jaasUserInfo = new JAASUserInfo(userInfo); try { jaasUserInfo.fetchRoles(); } catch (Exception ex) { if (_debug) { LOG.debug("Failed to fetch roles", ex); } throw new LoginException("Error obtaining user info."); } setCurrentUser(jaasUserInfo); setAuthenticated(true); return true; }
From source file:org.apache.openaz.xacml.std.pip.engines.ldap.ConfigurableLDAPResolver.java
private Attribute decodeResultValue(SearchResult searchResult, String view, PIPRequest viewRequest) { AttributeValue<?> attributeValue = null; Collection<AttributeValue<?>> attributeMultiValue = null; DataType<?> dataType = null;//from w ww . jav a2 s. com this.logger.warn("(" + id + ") " + "SearchResult attributes: " + searchResult.getAttributes()); try { dataType = dataTypeFactory.getDataType(viewRequest.getDataTypeId()); if (dataType == null) { if (this.logger.isTraceEnabled()) { this.logger.trace("(" + id + ") " + "Unknown data type in " + viewRequest); } return null; } if ("dn".equalsIgnoreCase(view)) { attributeValue = dataType.createAttributeValue(searchResult.getNameInNamespace()); } else { javax.naming.directory.Attribute dirAttr = searchResult.getAttributes().get(view); if (dirAttr != null) { if (this.logger.isTraceEnabled()) { this.logger.trace( "(" + id + ") " + "directory attribute '" + view + "' value is '" + dirAttr + "'"); } // we could guide this more elaborately by object class .. if (dirAttr.size() == 1) { attributeValue = dataType.createAttributeValue(dirAttr.get().toString()); } else { if (this.logger.isTraceEnabled()) { this.logger .trace("(" + id + ") " + "SearchResult yields a multi-valued '" + view + "'"); } attributeMultiValue = new HashSet<AttributeValue<?>>(); // we should for (int i = 0; i < dirAttr.size(); i++) { attributeMultiValue.add(dataType.createAttributeValue(dirAttr.get().toString())); } } } else { this.logger.warn("(" + id + ") " + "SearchResult did not provide a value for '" + view + "'"); return null; } } } catch (DataTypeException dtx) { this.logger.error("(" + id + ") " + "Failed to decode search result", dtx); return null; } catch (NamingException nx) { this.logger.error("(" + id + ") " + "Failed to decode search result", nx); return null; } Attribute attr = null; if (attributeMultiValue == null) { attr = new StdAttribute(viewRequest.getCategory(), viewRequest.getAttributeId(), attributeValue, viewRequest.getIssuer(), false); } else { attr = new StdAttribute(viewRequest.getCategory(), viewRequest.getAttributeId(), attributeMultiValue, viewRequest.getIssuer(), false); } this.logger.warn("(" + id + ") " + " providing attribute " + attr); return attr; }