當前位置: 首頁>>代碼示例>>Java>>正文


Java LdapContext類代碼示例

本文整理匯總了Java中javax.naming.ldap.LdapContext的典型用法代碼示例。如果您正苦於以下問題:Java LdapContext類的具體用法?Java LdapContext怎麽用?Java LdapContext使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


LdapContext類屬於javax.naming.ldap包,在下文中一共展示了LdapContext類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: getGroup

import javax.naming.ldap.LdapContext; //導入依賴的package包/類
public Group getGroup(String groupName) throws GroupNotFoundException {
    LdapContext ctx = null;
    try {
        String groupDN = manager.findGroupDN(groupName);
        // Load record.
        ctx = manager.getContext(manager.getGroupsBaseDN(groupName));
        Attributes attrs = ctx.getAttributes(groupDN, standardAttributes);

        return processGroup(ctx, attrs);
    }
    catch (Exception e) {
        Log.error(e.getMessage(), e);
        throw new GroupNotFoundException("Group with name " + groupName + " not found.", e);
    }
    finally {
        try {
            if (ctx != null) {
                ctx.setRequestControls(null);
                ctx.close();
            }
        }
        catch (Exception ignored) {
            // Ignore.
        }
    }
}
 
開發者ID:coodeer,項目名稱:g3server,代碼行數:27,代碼來源:LdapGroupProvider.java

示例2: queryForAuthenticationInfo

import javax.naming.ldap.LdapContext; //導入依賴的package包/類
/**
 * Builds an {@link AuthenticationInfo} object by querying the active directory LDAP context for the
 * specified username.
 */
@Override
protected AuthenticationInfo queryForAuthenticationInfo(
        AuthenticationToken token, LdapContextFactory ldapContextFactory) throws NamingException {

    final UsernamePasswordToken upToken = ensureUsernamePasswordToken(token);
    final String userDn = findUserDn(ldapContextFactory, upToken.getUsername());

    LdapContext ctx = null;
    try {
        // Binds using the username and password provided by the user.
        ctx = ldapContextFactory.getLdapContext(userDn, upToken.getPassword());
    } finally {
        LdapUtils.closeContext(ctx);
    }
    return buildAuthenticationInfo(upToken.getUsername(), upToken.getPassword());
}
 
開發者ID:line,項目名稱:centraldogma,代碼行數:21,代碼來源:SearchFirstActiveDirectoryRealm.java

示例3: authenticateAndAuthorize

import javax.naming.ldap.LdapContext; //導入依賴的package包/類
@Override
public AuthInfo authenticateAndAuthorize( AuthToken authToken ) throws AuthenticationException
{
    try
    {
        String username = authToken.principal();
        char[] password = authToken.credentials();

        api.log().info( "Log in attempted for user '" + username + "'.");

        LdapContext ctx = authenticate( username, password );

        api.log().info( "User '" + username + "' authenticated." );

        Set<String> roles = authorize( ctx, username );

        api.log().info( "User '" + username + "' authorized roles " + roles );

        return AuthInfo.of( username, roles );
    }
    catch ( NamingException e )
    {
        throw new AuthenticationException( e.getMessage() );
    }
}
 
開發者ID:neo4j,項目名稱:neo4j-example-auth-plugins,代碼行數:26,代碼來源:LdapGroupHasUsersAuthPlugin.java

示例4: queryForAuthenticationInfo

import javax.naming.ldap.LdapContext; //導入依賴的package包/類
/**
 * This implementation opens an LDAP connection using the token's
 * {@link #getLdapPrincipal(org.apache.shiro.authc.AuthenticationToken) discovered principal} and provided
 * {@link AuthenticationToken#getCredentials() credentials}.  If the connection opens successfully, the
 * authentication attempt is immediately considered successful and a new
 * {@link AuthenticationInfo} instance is
 * {@link #createAuthenticationInfo(org.apache.shiro.authc.AuthenticationToken, Object, Object, javax.naming.ldap.LdapContext) created}
 * and returned.  If the connection cannot be opened, either because LDAP authentication failed or some other
 * JNDI problem, an {@link NamingException} will be thrown.
 *
 * @param token              the submitted authentication token that triggered the authentication attempt.
 * @param ldapContextFactory factory used to retrieve LDAP connections.
 * @return an {@link AuthenticationInfo} instance representing the authenticated user's information.
 * @throws NamingException if any LDAP errors occur.
 */
protected AuthenticationInfo queryForAuthenticationInfo(AuthenticationToken token,
                                                        LdapContextFactory ldapContextFactory)
        throws NamingException {

    Object principal = token.getPrincipal();
    Object credentials = token.getCredentials();

    log.debug("Authenticating user '{}' through LDAP", principal);

    principal = getLdapPrincipal(token);

    LdapContext ctx = null;
    try {
        ctx = ldapContextFactory.getLdapContext(principal, credentials);
        //context was opened successfully, which means their credentials were valid.  Return the AuthenticationInfo:
        return createAuthenticationInfo(token, principal, credentials, ctx);
    } finally {
        LdapUtils.closeContext(ctx);
    }
}
 
開發者ID:xuegongzi,項目名稱:rabbitframework,代碼行數:36,代碼來源:DefaultLdapRealm.java

示例5: prepareNextPage

import javax.naming.ldap.LdapContext; //導入依賴的package包/類
private boolean prepareNextPage(LdapContext ldapContext) throws Exception {
    Control[] responseControls = ldapContext.getResponseControls();

    byte[] cookie = null;
    if (responseControls != null) {
        for (Control responseControl : responseControls) {
            if (responseControl instanceof PagedResultsResponseControl) {
                PagedResultsResponseControl prrc = (PagedResultsResponseControl) responseControl;
                cookie = prrc.getCookie();
            }
        }
    }

    if (cookie == null) {
        return false;
    } else {
        ldapContext.setRequestControls(new Control[]{new PagedResultsControl(pageSize, cookie, Control.CRITICAL)});
        return true;
    }
}
 
開發者ID:HydAu,項目名稱:Camel,代碼行數:21,代碼來源:LdapProducer.java

示例6: updateLdapZimbra

import javax.naming.ldap.LdapContext; //導入依賴的package包/類
public void updateLdapZimbra(LdapContext ctx ,User user,String name, Employee emp) throws NamingException{
	Modifications mods = Modifications.getInstance();
       for (int i = 0; i < 5;i++){
       	 mods.addItem(zimbraProperty[i][0],zimbraProperty[i][1]);
       }
       mods.addItem("zimbramaildeliveryaddress",user.getEmailAddress());
    
      // mods.addItem("company",user.getEmailAddress());
     //  mods.addItem("street",user.getEmailAddress());
      //.addItem("company",user.getEmailAddress());
      // mods.addItem("company",user.getEmailAddress());
   	//System.out.println("My  " + mods);
       ModificationItem[] modItems = mods.getItems();
       ctx.modifyAttributes(name, modItems);
       //= getContext(serviceContext.getCompanyId());
	
}
 
開發者ID:openegovplatform,項目名稱:OEPv2,代碼行數:18,代碼來源:EmployeeExportToLdap.java

示例7: defineTriggerExecutionSpecificPoint

import javax.naming.ldap.LdapContext; //導入依賴的package包/類
/**
 * Defines the Administration point and administrative role for the TriggerExecution specific point
 * @param apCtx The administrative point context
 * @throws NamingException If the operation failed
 */
public static void defineTriggerExecutionSpecificPoint( LdapContext apCtx ) throws NamingException
{
    Attributes ap = apCtx.getAttributes( "", new String[] { SchemaConstants.ADMINISTRATIVE_ROLE_AT } );
    Attribute administrativeRole = ap.get( SchemaConstants.ADMINISTRATIVE_ROLE_AT );
    
    if ( administrativeRole == null
        || !AttributeUtils.containsValueCaseIgnore( administrativeRole, SchemaConstants.TRIGGER_EXECUTION_SPECIFIC_AREA ) )
    {
        Attributes changes = new BasicAttributes( SchemaConstants.ADMINISTRATIVE_ROLE_AT,
            SchemaConstants.TRIGGER_EXECUTION_SPECIFIC_AREA, true );
        apCtx.modifyAttributes( "", DirContext.ADD_ATTRIBUTE, changes );
    }
}
 
開發者ID:apache,項目名稱:directory-ldap-api,代碼行數:19,代碼來源:TriggerUtils.java

示例8: createTriggerExecutionSubentry

import javax.naming.ldap.LdapContext; //導入依賴的package包/類
/**
 * Create the Trigger execution subentry
 * 
 * @param apCtx The administration point context
 * @param subentryCN The CN used by the suentry
 * @param subtreeSpec The subtree specification
 * @param prescriptiveTriggerSpec The prescriptive trigger specification
 * @throws NamingException If the operation failed
 */
public static void createTriggerExecutionSubentry(
    LdapContext apCtx,
    String subentryCN,
    String subtreeSpec,
    String prescriptiveTriggerSpec ) throws NamingException
{
    Attributes subentry = new BasicAttributes( SchemaConstants.CN_AT, subentryCN, true );
    Attribute objectClass = new BasicAttribute( SchemaConstants.OBJECT_CLASS_AT );
    subentry.put( objectClass );
    objectClass.add( SchemaConstants.TOP_OC );
    objectClass.add( SchemaConstants.SUBENTRY_OC );
    objectClass.add( SchemaConstants.TRIGGER_EXECUTION_SUBENTRY_OC );
    subentry.put( SchemaConstants.SUBTREE_SPECIFICATION_AT, subtreeSpec );
    subentry.put( SchemaConstants.PRESCRIPTIVE_TRIGGER_SPECIFICATION_AT, prescriptiveTriggerSpec );
    apCtx.createSubcontext( "cn=" + subentryCN, subentry );
}
 
開發者ID:apache,項目名稱:directory-ldap-api,代碼行數:26,代碼來源:TriggerUtils.java

示例9: clearLdapContext

import javax.naming.ldap.LdapContext; //導入依賴的package包/類
private void clearLdapContext(String action) {

        try {
            loggerInfo("LDAPContext", "清空", "開始", action);

            if (ldapContexts.containsKey(action)) {
                LdapContext context = ldapContexts.get(action);
                context.close();
                context = null;
                ldapContexts.remove(action);
            }

            loggerInfo("LDAPContext", "清空", "完成", action);
        }
        catch (Exception e) {
            loggerError("LDAPContext清空", action, e);
        }

    }
 
開發者ID:uavorg,項目名稱:uavstack,代碼行數:20,代碼來源:GUISSOLdapClient.java

示例10: getContext

import javax.naming.ldap.LdapContext; //導入依賴的package包/類
private LdapContext getContext() throws Exception {
	Hashtable<String, String> envDC = new Hashtable<String, String>();
	envDC.put(
			Context.INITIAL_CONTEXT_FACTORY,
			"com.sun.jndi.ldap.LdapCtxFactory");
	envDC.put(
			Context.PROVIDER_URL,
			GlobalProperties.getInstance().getProperty("app.persones.plugin.ldap.url"));
	envDC.put(
			Context.SECURITY_AUTHENTICATION,
			"simple");
	envDC.put(
			Context.SECURITY_PRINCIPAL,
			GlobalProperties.getInstance().getProperty("app.persones.plugin.ldap.principal"));
	envDC.put(
			Context.SECURITY_CREDENTIALS,
			GlobalProperties.getInstance().getProperty("app.persones.plugin.ldap.credentials"));
	return new InitialLdapContext(envDC, null);
}
 
開發者ID:GovernIB,項目名稱:helium,代碼行數:20,代碼來源:PersonesPluginLdap.java

示例11: addConfiguration

import javax.naming.ldap.LdapContext; //導入依賴的package包/類
@Override
public LdapConfigurationResponse addConfiguration(final String hostname, final int port) throws InvalidParameterValueException {
    LdapConfigurationVO configuration = _ldapConfigurationDao.findByHostname(hostname);
    if (configuration == null) {
        LdapContext context = null;
        try {
            final String providerUrl = "ldap://" + hostname + ":" + port;
            context = _ldapContextFactory.createBindContext(providerUrl);
            configuration = new LdapConfigurationVO(hostname, port);
            _ldapConfigurationDao.persist(configuration);
            s_logger.info("Added new ldap server with hostname: " + hostname);
            return new LdapConfigurationResponse(hostname, port);
        } catch (NamingException | IOException e) {
            s_logger.debug("NamingException while doing an LDAP bind", e);
            throw new InvalidParameterValueException("Unable to bind to the given LDAP server");
        } finally {
            closeContext(context);
        }
    } else {
        throw new InvalidParameterValueException("Duplicate configuration");
    }
}
 
開發者ID:MissionCriticalCloud,項目名稱:cosmic,代碼行數:23,代碼來源:LdapManagerImpl.java

示例12: getUsersInGroup

import javax.naming.ldap.LdapContext; //導入依賴的package包/類
@Override
public List<LdapUser> getUsersInGroup(final String groupName, final LdapContext context) throws NamingException {
    if (StringUtils.isBlank(groupName)) {
        throw new IllegalArgumentException("ldap group name cannot be blank");
    }

    final String basedn = _ldapConfiguration.getBaseDn();
    if (StringUtils.isBlank(basedn)) {
        throw new IllegalArgumentException("ldap basedn is not configured");
    }

    final SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(_ldapConfiguration.getScope());
    searchControls.setReturningAttributes(_ldapConfiguration.getReturnAttributes());

    final NamingEnumeration<SearchResult> results = context.search(basedn, generateADGroupSearchFilter(groupName), searchControls);
    final List<LdapUser> users = new ArrayList<>();
    while (results.hasMoreElements()) {
        final SearchResult result = results.nextElement();
        users.add(createUser(result));
    }
    return users;
}
 
開發者ID:MissionCriticalCloud,項目名稱:cosmic,代碼行數:24,代碼來源:ADLdapUserManagerImpl.java

示例13: searchUser

import javax.naming.ldap.LdapContext; //導入依賴的package包/類
public LdapUser searchUser(final String basedn, final String searchString, final LdapContext context) throws NamingException, IOException {
    final SearchControls searchControls = new SearchControls();

    searchControls.setSearchScope(_ldapConfiguration.getScope());
    searchControls.setReturningAttributes(_ldapConfiguration.getReturnAttributes());

    final NamingEnumeration<SearchResult> results = context.search(basedn, searchString, searchControls);
    final List<LdapUser> users = new ArrayList<>();
    while (results.hasMoreElements()) {
        final SearchResult result = results.nextElement();
        users.add(createUser(result));
    }

    if (users.size() == 1) {
        return users.get(0);
    } else {
        throw new NamingException("No user found for basedn " + basedn + " and searchString " + searchString);
    }
}
 
開發者ID:MissionCriticalCloud,項目名稱:cosmic,代碼行數:20,代碼來源:OpenLdapUserManagerImpl.java

示例14: queryForAuthorizationInfo

import javax.naming.ldap.LdapContext; //導入依賴的package包/類
/**
 * Builds an {@link org.apache.shiro.authz.AuthorizationInfo} object by querying the active directory LDAP context for the
 * groups that a user is a member of.  The groups are then translated to role names by using the
 * configured {@link #groupRolesMap}.
 * <p/>
 * This implementation expects the <tt>principal</tt> argument to be a String username.
 * <p/>
 * Subclasses can override this method to determine authorization data (roles, permissions, etc) in a more
 * complex way.  Note that this default implementation does not support permissions, only roles.
 *
 * @param principals         the principal of the Subject whose account is being retrieved.
 * @param ldapContextFactory the factory used to create LDAP connections.
 * @return the AuthorizationInfo for the given Subject principal.
 * @throws NamingException if an error occurs when searching the LDAP server.
 */
protected AuthorizationInfo queryForAuthorizationInfo(PrincipalCollection principals, LdapContextFactory ldapContextFactory) throws NamingException {

    String username = (String) getAvailablePrincipal(principals);

    // Perform context search
    LdapContext ldapContext = ldapContextFactory.getSystemLdapContext();

    Set<String> roleNames;

    try {
        roleNames = getRoleNamesForUser(username, ldapContext);
    } finally {
        LdapUtils.closeContext(ldapContext);
    }

    return buildAuthorizationInfo(roleNames);
}
 
開發者ID:xuegongzi,項目名稱:rabbitframework,代碼行數:33,代碼來源:ActiveDirectoryRealm.java

示例15: process

import javax.naming.ldap.LdapContext; //導入依賴的package包/類
public void process(Exchange exchange) throws Exception {
    String filter = exchange.getIn().getBody(String.class);
    DirContext dirContext = getDirContext();

    try {
        // could throw NamingException
        List<SearchResult> data;
        if (pageSize == null) {
            data = simpleSearch(dirContext, filter);
        } else {
            if (!(dirContext instanceof LdapContext)) {
                throw new IllegalArgumentException("When using attribute 'pageSize' for a ldap endpoint, you must provide a LdapContext (subclass of DirContext)");
            }
            data = pagedSearch((LdapContext) dirContext, filter);
        }
        exchange.getOut().setBody(data);
        exchange.getOut().setHeaders(exchange.getIn().getHeaders());
        exchange.getOut().setAttachments(exchange.getIn().getAttachments());
    } finally {
        if (dirContext != null) {
            dirContext.close();
        }
    }
}
 
開發者ID:HydAu,項目名稱:Camel,代碼行數:25,代碼來源:LdapProducer.java


注:本文中的javax.naming.ldap.LdapContext類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。