茫茫網海中的冷日
         
茫茫網海中的冷日
發生過的事,不可能遺忘,只是想不起來而已!
 恭喜您是本站第 1704353 位訪客!  登入  | 註冊
主選單

Google 自訂搜尋

Goole 廣告

隨機相片
IMG_0263.jpg

授權條款

使用者登入
使用者名稱:

密碼:


忘了密碼?

現在就註冊!

爪哇咖啡屋 : [轉貼]java 如何呼叫 ldap 協議

發表者 討論內容
冷日
(冷日)
Webmaster
  • 註冊日: 2008/2/19
  • 來自:
  • 發表數: 15771
[轉貼]java 如何呼叫 ldap 協議

java如何呼叫ldap協議【LdapContext】

java教程 · 發表


背景:

做了個系統需要用集團的使用者id登入。而集團使用者系統是用ldap做的。


關鍵知識點
1. 設定連線
ctx = new InitialLdapContext(env, connCtls);
2.設定url和查詢的子路徑
env.put(Context.PROVIDER_URL, URL);// LDAP serverenv.put(Context.SECURITY_PRINCIPAL, SEARCHDN);
3. 設定密碼
env.put(Context.SECURITY_CREDENTIALS, "password");

4.取得返回值屬性
if (obj instanceof SearchResult) {SearchResult si = (SearchResult) obj;Attributes userInfo = si.getAttributes();userDN += userInfo.toString();userDN += "," + BASEDN;}
5.不需要下載任何第三方辦,什麼ldapjdk.jar不用的
背景知識:


LDAP是輕量目錄訪問協議,英文全稱是Lightweight Directory Access Protocol,一般都簡稱為LDAP。它是基於X.500標準的,但是簡單多了並且可以根據需要定製。與X.500不同,LDAP支援TCP/IP,這對訪問Internet是必須的。LDAP的核心規範在RFC中都有定義,所有與LDAP相關的RFC都可以在LDAPman RFC網頁中找到

附原始碼如下:

package com.domain;

import java.util.Hashtable;
import javax.naming.AuthenticationException;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attributes;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.Control;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;

public class UserAuthenticate {
	private String URL = "ldap://localhost:389";
	private String SEARCHDN = "CN=alimailfad,OU=service,DC=hz,DC=ali,DC=com";
	private String FACTORY = "com.sun.jndi.ldap.LdapCtxFactory";
	private String BASEDN = "DC=hz,DC=ali,DC=com";
	private LdapContext ctx = null;
	private Hashtable env = null;
	private Control[] connCtls = null;

	private void LDAP_connect() {
		env = new Hashtable();
		env.put(Context.INITIAL_CONTEXT_FACTORY, FACTORY);
		env.put(Context.PROVIDER_URL, URL);
		// LDAP server env.put(Context.SECURITY_PRINCIPAL, SEARCHDN);
		env.put(Context.SECURITY_AUTHENTICATION, "simple");
		env.put(Context.SECURITY_CREDENTIALS, "password");
		// 此處若不指定使用者名稱和密碼,則自動轉換為匿名登入
		try {
			ctx = new InitialLdapContext(env, connCtls);
		} catch (NamingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private String getUserDN(String email) {
		String userDN = "";
		LDAP_connect();
		try {
			String filters = "(&;(&;(objectCategory=person)(objectClass=user))(sAMAccountName=elbert.chenh))";
			String[] returnedAtts = { "distinguishedName", "userAccountControl", "displayName", "employeeID" };
			SearchControls constraints = new SearchControls();
			constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
			if (returnedAtts != null && returnedAtts.length > 0) {
				constraints.setReturningAttributes(returnedAtts);
			}
			NamingEnumeration en = ctx.search(BASEDN, filters, constraints);
			if (en == null) {
				System.out.println("Have no NamingEnumeration.");
			}
			if (!en.hasMoreElements()) {
				System.out.println("Have no element.");
			} else {
				while (en != null && en.hasMoreElements()) {
					Object obj = en.nextElement();
					if (obj instanceof SearchResult) {
						SearchResult si = (SearchResult) obj;
						Attributes userInfo = si.getAttributes();
						userDN += userInfo.toString();
						userDN += "," + BASEDN;
					} else {
						System.out.println(obj.toString());
					}
					System.out.println(userDN);
				}
			}
		} catch (Exception e) {
			System.out.println("Exception in search():" + e);
		}
		return userDN;
	}

	public boolean authenricate(String ID, String password) {
		boolean valide = false;
		String userDN = getUserDN(ID);
		try {
			ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, userDN);
			ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, password);
			ctx.reconnect(connCtls);
			System.out.println(userDN + " is authenticated");
			valide = true;
		} catch (AuthenticationException e) {
			System.out.println(userDN + " is not authenticated");
			System.out.println(e.toString());
			valide = false;
		} catch (NamingException e) {
			System.out.println(userDN + " is not authenticated");
			valide = false;
		}
		return valide;
	}
}



原文出處: java如何呼叫ldap協議【LdapContext】 - IT閱讀
參考資料:javax.naming.ldap (Java Platform SE 7 )
冷日
(冷日)
Webmaster
  • 註冊日: 2008/2/19
  • 來自:
  • 發表數: 15771
[轉貼]Java InitialLdapContext 類代碼示例

Java InitialLdapContext類代碼示例

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

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

示例1: getContext


import javax.naming.ldap.InitialLdapContext; //導入依賴的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


示例2: init


import javax.naming.ldap.InitialLdapContext; //導入依賴的package包/類
private void init()
throws Exception
{
@SuppressWarnings("UseOfObsoleteCollectionType")
Hashtable<String,String> env = new Hashtable<>();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, sdsUrl);
if (ConditionalCompilationControls.LDAPS && !ConditionalCompilationControls.OPENTEST) {
env.put(Context.SECURITY_PROTOCOL, "ssl");
env.put(Context.SECURITY_AUTHENTICATION, "none");
if (ConditionalCompilationControls.LDAPOVERTLS && !ConditionalCompilationControls.OPENTEST) {
env.put("java.naming.ldap.factory.socket", "org.warlock.spine.connection.SpineSecurityContext");
}
}
ldapContext = new InitialLdapContext(env, null);
}

開發者ID:DamianJMurphy, 項目名稱:SpineTools-Java, 代碼行數:17, 代碼來源: SDSconnection.java


示例3: setSchemaContext


import javax.naming.ldap.InitialLdapContext; //導入依賴的package包/類
private void setSchemaContext(KdcConfiguration configuration, DirectoryService service,
String connectionUser)
throws DirectoryServerException {
Hashtable<String, Object> env = new Hashtable<String, Object>();
env.put(DirectoryService.JNDI_KEY, service);
env.put(Context.SECURITY_PRINCIPAL, connectionUser);
env.put(Context.SECURITY_CREDENTIALS, configuration.getSystemAdminPassword());
env.put(Context.SECURITY_AUTHENTICATION, ConfigurationConstants.SIMPLE_AUTHENTICATION);
env.put(Context.INITIAL_CONTEXT_FACTORY, CoreContextFactory.class.getName());
env.put(Context.PROVIDER_URL, SchemaConstants.OU_SCHEMA);
try {
schemaRoot = new InitialLdapContext(env, null);
} catch (NamingException e) {
throw new DirectoryServerException(
"Unable to create Schema context with user " + connectionUser, e);
}
}

開發者ID:wso2-attic, 項目名稱:carbon-identity, 代碼行數:21, 代碼來源: ApacheKDCServer.java


示例4: bindDNReferralAuthentication


import javax.naming.ldap.InitialLdapContext; //導入依賴的package包/類
/**
* This method validates absoluteName and credential against referral LDAP and returns used user DN.
*
* <ol>
* <li> Parses given absoluteName to URL and DN
* <li> creates initial LDAP context of referral LDAP to validate credential
* <li> closes the initial context
* </ol>
*
* It uses all options from login module setup except of ProviderURL.
*
* @param userDN - userDN which has to be used instead of parsed absoluteName (if is null, use absoluteName) - value is gained using distinguishedNameAttribute
* @param absoluteName - absolute user DN
* @param credential
* @return used user DN for validation
* @throws NamingException
*/
private String bindDNReferralAuthentication(final String userDN, String absoluteName, Object credential)
throws NamingException
{
URI uri;
try {
uri = new URI(absoluteName);
}
catch (URISyntaxException e)
{
throw PicketBoxMessages.MESSAGES.unableToParseReferralAbsoluteName(e, absoluteName);
}
String name = (userDN != null ? userDN : uri.getPath().substring(1));
String namingProviderURL = uri.getScheme() + "://" + uri.getAuthority();
Properties refEnv = constructLdapContextEnvironment(namingProviderURL, name, credential);
InitialLdapContext refCtx = new InitialLdapContext(refEnv, null);
refCtx.close();
return name;
}

開發者ID:picketbox, 項目名稱:picketbox, 代碼行數:38, 代碼來源: LdapExtLoginModule.java


示例5: testGetControlInstanceControl


import javax.naming.ldap.InitialLdapContext; //導入依賴的package包/類
/**
* <p>Test method for 'javax.naming.ldap.ControlFactory.getControlInstance(Control)'</p>
* <p>Here we are going to test if we can get an instance with the controls sended.</p>
*/
public void testGetControlInstanceControl() {
try {
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY,"org.apache.harmony.jndi.tests.javax.naming.spi.mock.ldap.MockContextFactory");
MockControl[] cs = { new MockControl("c1", false, new byte[] { 1, 2, 3, 4 }),
new MockControl("c1", true, new byte[] { 'a', 'b', 'c', 'd' }), };
MockControl cs2 = new MockControl("c1", false, new byte[] { 1, 2, 3, 4 });
InitialLdapContext ilc=new InitialLdapContext(env, cs);
assertEquals(cs2,ControlFactory.getControlInstance(cs2,ilc,env));
} catch (NamingException e) {
}
}

開發者ID:shannah, 項目名稱:cn1, 代碼行數:21, 代碼來源: TestControlFactoryWhiteBoxDevelopment.java


示例6: testReconnect003


import javax.naming.ldap.InitialLdapContext; //導入依賴的package包/類
/**
* <p>
* Test method for
* 'javax.naming.ldap.InitialLdapContext.reconnect(Control[])'
* </p>
* <p>
* Here we are testing if this method correctly reconnects to the LDAP
* server. In this case we are using a different set of controls for the
* reconnection.
* </p>
* <p>
* The expected result is a reconection with the new set of controls.
* </p>
*/
public void testReconnect003() throws Exception {
System
.setProperty(Context.INITIAL_CONTEXT_FACTORY,
"org.apache.harmony.jndi.tests.javax.naming.spi.mock.ldap.MockContextFactory");
Control[] cs = {
new MockControl("c1", false, new byte[] { 1, 2, 3, 4 }),
new MockControl("c1", true, new byte[] { 'a', 'b', 'c', 'd' }), };
Control[] cs2 = {
new MockControl("c2", false, new byte[] { 1, 2, 3, 4 }),
new MockControl("c2", true, new byte[] { 'a', 'b', 'c', 'd' }), };
InitialLdapContext ilc = new InitialLdapContext(null, cs);
ilc.reconnect(cs2);
assertEquals(cs2, ilc.getConnectControls());
ilc.close();
}

開發者ID:shannah, 項目名稱:cn1, 代碼行數:30, 代碼來源: TestInitialLdapContext.java


示例7: testConnectControls3


import javax.naming.ldap.InitialLdapContext; //導入依賴的package包/類
public void testConnectControls3() throws Exception {
// set connect controls by InitialLdapContext
server.setResponseSeq(new LdapMessage[] { new LdapMessage(
LdapASN1Constant.OP_BIND_RESPONSE, new BindResponse(), null) });
InitialLdapContext initialDirContext = new InitialLdapContext(env,
new Control[] { new SortControl("", Control.NONCRITICAL) });
server.setResponseSeq(new LdapMessage[] { new LdapMessage(
LdapASN1Constant.OP_SEARCH_RESULT_DONE,
new EncodableLdapResult(), null) });
LdapContext context = (LdapContext) initialDirContext.lookup("");
Control[] controls = context.getConnectControls();
assertNotNull(controls);
assertEquals(1, controls.length);
Control c = controls[0];
assertTrue(c instanceof SortControl);
assertEquals(Control.NONCRITICAL, c.isCritical());
}

開發者ID:shannah, 項目名稱:cn1, 代碼行數:21, 代碼來源: LdapContextServerMockedTest.java


示例8: findAccountByAccountName


import javax.naming.ldap.InitialLdapContext; //導入依賴的package包/類
/**
* Find account by account name.
*
* @param accountName the account name
* @return the search result
* @throws NamingException the naming exception
*/
protected SearchResult findAccountByAccountName(String accountName) throws NamingException {
String searchFilter = String.format(searchFilterPattern, accountName);
SearchControls searchControls = new SearchControls();
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
InitialLdapContext ctx = new InitialLdapContext(env, null);
try {
NamingEnumeration<SearchResult> results = ctx.search(searchBase, searchFilter, searchControls);
if (!results.hasMoreElements()) {
throw new UserConfigLoaderException("LDAP Search returned no accounts");
}
SearchResult searchResult = results.nextElement();
if (results.hasMoreElements()) {
throw new UserConfigLoaderException("More than one account found in ldap search");
}
return searchResult;
} finally {
ctx.close();
}
}

開發者ID:apache, 項目名稱:lens, 代碼行數:27, 代碼來源: LDAPBackedDatabaseUserConfigLoader.java


示例9: testGetControlInstanceControl


import javax.naming.ldap.InitialLdapContext; //導入依賴的package包/類
/**
* <p>Test method for 'javax.naming.ldap.ControlFactory.getControlInstance(Control)'</p>
* <p>Here we are gonna test if we can get an instance with the controls sended.</p>
*/
public void testGetControlInstanceControl() {
try {
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY,"org.apache.harmony.jndi.tests.javax.naming.spi.mock.ldap.MockContextFactory");
MockControl[] cs = { new MockControl("c1", false, new byte[] { 1, 2, 3, 4 }),
new MockControl("c1", true, new byte[] { 'a', 'b', 'c', 'd' }), };
MockControl cs2 = new MockControl("c1", false, new byte[] { 1, 2, 3, 4 });
InitialLdapContext ilc=new InitialLdapContext(env, cs);
assertEquals(cs2,ControlFactory.getControlInstance(cs2,ilc,env));
} catch (NamingException e) {
}
}

開發者ID:freeVM, 項目名稱:freeVM, 代碼行數:21, 代碼來源: TestControlFactoryWhiteBoxDevelopment.java


示例10: testReconnect003


import javax.naming.ldap.InitialLdapContext; //導入依賴的package包/類
/**
* <p>
* Test method for
* 'javax.naming.ldap.InitialLdapContext.reconnect(Control[])'
* </p>
* <p>
* Here we are testing if this method reconnects to the LDAP server using
* the supplied controls and this context's environment. In this case we are
* sending a new set of controls to reconection.
* </p>
* <p>
* The expected result is a reconection with the new set of controls.
* </p>
*/
public void testReconnect003() throws Exception {
System
.setProperty(Context.INITIAL_CONTEXT_FACTORY,
"org.apache.harmony.jndi.tests.javax.naming.spi.mock.ldap.MockContextFactory");
Control[] cs = {
new MockControl("c1", false, new byte[] { 1, 2, 3, 4 }),
new MockControl("c1", true, new byte[] { 'a', 'b', 'c', 'd' }), };
Control[] cs2 = {
new MockControl("c2", false, new byte[] { 1, 2, 3, 4 }),
new MockControl("c2", true, new byte[] { 'a', 'b', 'c', 'd' }), };
InitialLdapContext ilc = new InitialLdapContext(null, cs);
ilc.reconnect(cs2);
assertEquals(cs2, ilc.getConnectControls());
ilc.close();
}

開發者ID:freeVM, 項目名稱:freeVM, 代碼行數:30, 代碼來源: TestInitialLdapContext.java


示例11: setUp


import javax.naming.ldap.InitialLdapContext; //導入依賴的package包/類
protected void setUp() throws Exception {
super.setUp();
configuration = new MutableServerStartupConfiguration();
configuration.setWorkingDirectory(new File(workingDir));
cleanWorkingDir(configuration.getWorkingDirectory());
port = AvailablePortFinder.getNextAvailable(1024);
configuration.setLdapPort(port);
// configuration.setShutdownHookEnabled(false);
serverEnv = new Hashtable<String, Object>(configuration
.toJndiEnvironment());
initialAuth();
serverEnv.put(Context.INITIAL_CONTEXT_FACTORY,
ServerContextFactory.class.getName());
serverEnv.put(Context.PROVIDER_URL, "");
rootDSE = new InitialLdapContext(serverEnv, null);
}

開發者ID:freeVM, 項目名稱:freeVM, 代碼行數:21, 代碼來源: Support_LdapTest.java


示例12: getFullyQualifiedNameByUserId


import javax.naming.ldap.InitialLdapContext; //導入依賴的package包/類
protected String getFullyQualifiedNameByUserId(String userId) throws UnauthorizedOperationException {
env.put(Context.SECURITY_PRINCIPAL, ctxPrinciplePattern.replaceAll(userNamePattern, delegatedUserName));
env.put(Context.SECURITY_CREDENTIALS, delegatedUserPassword);
try {
LdapContext ctx = new InitialLdapContext(env,null);
String searchFilter = searchFilterPattern.replaceAll(userNamePattern, userId);
SearchControls searchControls = new SearchControls();
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration<SearchResult> results = ctx.search(ldapSearchBase,
searchFilter, searchControls);
SearchResult searchResult = null;
if (results.hasMoreElements()) {
searchResult = results.nextElement();
return searchResult.getNameInNamespace();
}
return null;
} catch (NamingException e) {
throw new UnauthorizedOperationException(e.getMessage());
}
}

開發者ID:ndexbio, 項目名稱:ndex-rest, 代碼行數:25, 代碼來源: LDAPAuthenticator.java


示例13: createContext


import javax.naming.ldap.InitialLdapContext; //導入依賴的package包/類
public LdapContext createContext()
{
init();
final Hashtable<String, String> env;
final String authentication = ldapConfig.getAuthentication();
if ("none".equals(authentication) == false) {
env = createEnv(ldapConfig.getManagerUser(), ldapConfig.getManagerPassword());
} else {
env = createEnv(null, null);
}
try {
final LdapContext ctx = new InitialLdapContext(env, null);
return ctx;
} catch (final NamingException ex) {
log.error("While trying to connect LDAP initally: " + ex.getMessage(), ex);
throw new RuntimeException(ex);
}
}

開發者ID:micromata, 項目名稱:projectforge-webapp, 代碼行數:19, 代碼來源: LdapConnector.java


示例14: ActiveDirectory


import javax.naming.ldap.InitialLdapContext; //導入依賴的package包/類
public ActiveDirectory(String serverName, String username, String password,
String domain) throws NamingException {
if (StringUtils.isEmpty(domain))
throw new NamingException("The domain is empty");
Properties properties = new Properties();
properties.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
domainSearchName = getDomainSearch(domain);
String login = StringUtils.fastConcat(username, "@", domain);
if (serverName != null) {
properties.put(Context.PROVIDER_URL,
StringUtils.fastConcat("ldap://", serverName, ":389"));
}
properties.put(Context.SECURITY_PRINCIPAL, login);
properties.put(Context.SECURITY_CREDENTIALS, password);
properties.put(Context.REFERRAL, "follow");
properties.put("java.naming.ldap.attributes.binary", "objectSID");
dirContext = new InitialLdapContext(properties, null);
}

開發者ID:jaeksoft, 項目名稱:opensearchserver, 代碼行數:21, 代碼來源: ActiveDirectory.java


示例15: getCurrentSession


import javax.naming.ldap.InitialLdapContext; //導入依賴的package包/類
/**
* Return the session which the current thread holds. If not exist, a new
* session will be created and bind to current thread.
*
* @return
*/
@Override
public Session getCurrentSession() {
Map.Entry<Session, InitialLdapContext> current = sessions.get();
if (null == current) {
try {
InitialLdapContext ldapConnection = getContext();
Session session = new SessionImpl(this, ldapConnection, true);
current = new AbstractMap.SimpleEntry<Session, InitialLdapContext>(
session, ldapConnection);
} catch (NamingException e) {
throw new ODMException("Cannot instantiate a session", e);
}
}
return current.getKey();
}

開發者ID:xingyuli, 項目名稱:some-ldap, 代碼行數:22, 代碼來源: AbstractThreadLocalSessionFactory.java


示例16: getDirContextInstance


import javax.naming.ldap.InitialLdapContext; //導入依賴的package包/類
@Override
protected DirContext getDirContextInstance(Hashtable<String, Object> env) throws NamingException {
String url = (String) env.get(Context.PROVIDER_URL);
try {
if (new URI(url).getScheme().equalsIgnoreCase("ldaps")) {
env.put("java.naming.ldap.factory.socket", "cz.inqool.uas.security.ldap.ssl.DummySSLSocketFactory");
}
} catch (URISyntaxException e) {
log.error("LDAP URL {} is wrong", url, e);
}
return new InitialLdapContext(env, null);
}

開發者ID:LIBCAS, 項目名稱:ARCLib, 代碼行數:13, 代碼來源: DummySSLLdapContextSource.java


示例17: userList


import javax.naming.ldap.InitialLdapContext; //導入依賴的package包/類
public static ArrayList<String> userList()
{
loadAdmindetails();
System.out.println("Details Loaded");
Properties props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
props.put(Context.PROVIDER_URL, url);
props.put(Context.SECURITY_PRINCIPAL, "cn="+ldapadminuname+",dc=serverless,dc=com");//adminuser - User with special priviledge, dn user
props.put(Context.SECURITY_CREDENTIALS, ldapadminpassword);//dn user password
ArrayList<String> resp = new ArrayList<String>();
try {
LdapContext ctx = new InitialLdapContext(props, null);
ctx.setRequestControls(null);
NamingEnumeration<?> namingEnum = ctx.search("ou=ias,dc=serverless,dc=com", "(objectclass=posixAccount)", AuthenticationService.getSimpleSearchControls());
while (namingEnum.hasMore ()) {
SearchResult result = (SearchResult) namingEnum.next ();
Attributes attrs = result.getAttributes ();
resp.add(attrs.get("cn").toString().substring(4));
}
namingEnum.close();
} catch (Exception e) {
e.printStackTrace();
}
return resp;
}

開發者ID:hemantverma1, 項目名稱:ServerlessPlatform, 代碼行數:28, 代碼來源: AuthenticationService.java


示例18: getByDn


import javax.naming.ldap.InitialLdapContext; //導入依賴的package包/類
public Attributes getByDn(final String dn) throws NamingException {
LdapContext ctx = new InitialLdapContext(env, null);
Attributes result = ctx.getAttributes(dn);
ctx.close();
return result;
}

開發者ID:klenkes74, 項目名稱:openshift-ldapsync, 代碼行數:8, 代碼來源: LdapServer.java


示例19: search


import javax.naming.ldap.InitialLdapContext; //導入依賴的package包/類
public NamingEnumeration<SearchResult> search(final String baseDN, final String filter) throws NamingException {
SearchControls searchControls = new SearchControls();
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
LdapContext ctx = new InitialLdapContext(env, null);
NamingEnumeration<SearchResult> result = ctx.search(baseDN, filter, searchControls);
ctx.close();
return result;
}

開發者ID:klenkes74, 項目名稱:openshift-ldapsync, 代碼行數:11, 代碼來源: LdapServer.java


示例20: startKerberos


import javax.naming.ldap.InitialLdapContext; //導入依賴的package包/類
@SuppressWarnings("unused")
private ApacheDS startKerberos() throws Exception {
Preconditions.checkState(ldapServer.isStarted());
kdcServer.setDirectoryService(directoryService);
// FIXME hard-coded ports
kdcServer.setTransports(new TcpTransport(6088), new UdpTransport(6088));
kdcServer.setEnabled(true);
kdcServer.setPrimaryRealm(realm);
kdcServer.setSearchBaseDn(baseDn);
kdcServer.setKdcPrincipal("krbtgt/" + realm + "@" + baseDn);
kdcServer.start();
// -------------------------------------------------------------------
// Enable the krb5kdc schema
// -------------------------------------------------------------------
Hashtable<String, Object> env = new Hashtable<String, Object>();
env.put(DirectoryService.JNDI_KEY, directoryService);
env.put(Context.INITIAL_CONTEXT_FACTORY, CoreContextFactory.class.getName());
env.put(Context.PROVIDER_URL, ServerDNConstants.OU_SCHEMA_DN);
InitialLdapContext schemaRoot = new InitialLdapContext(env, null);
// check if krb5kdc is disabled
Attributes krb5kdcAttrs = schemaRoot.getAttributes("cn=Krb5kdc");
boolean isKrb5KdcDisabled = false;
if (krb5kdcAttrs.get("m-disabled") != null) {
isKrb5KdcDisabled = ((String) krb5kdcAttrs.get("m-disabled").get()).equalsIgnoreCase("TRUE");
}
// if krb5kdc is disabled then enable it
if (isKrb5KdcDisabled) {
Attribute disabled = new BasicAttribute("m-disabled");
ModificationItem[] mods = new ModificationItem[] {new ModificationItem(DirContext.REMOVE_ATTRIBUTE, disabled)};
schemaRoot.modifyAttributes("cn=Krb5kdc", mods);
}
return this;
}

開發者ID:SonarQubeCommunity, 項目名稱:sonar-activedirectory, 代碼行數:39, 代碼來源: ApacheDS.java



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


原文出處:Java InitialLdapContext類代碼示例 - 純淨天空
冷日
(冷日)
Webmaster
  • 註冊日: 2008/2/19
  • 來自:
  • 發表數: 15771
[轉貼]javax.naming.ldap.LdapContext.search 代碼示例

Java LdapContext.search方法代碼示例

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

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

示例1: 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


示例2: 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


示例3: getRoleNamesForUser


import javax.naming.ldap.LdapContext; //導入方法依賴的package包/類
public Set<String> getRoleNamesForUser(String username,
LdapContext ldapContext,
String userDnTemplate) throws NamingException {
try {
Set<String> roleNames = new LinkedHashSet<>();
SearchControls searchCtls = new SearchControls();
searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
String searchFilter = "(&(objectClass=groupOfNames)(member=" + userDnTemplate + "))";
Object[] searchArguments = new Object[]{username};
NamingEnumeration<?> answer = ldapContext.search(
String.valueOf(ldapContext.getEnvironment().get("ldap.searchBase")),
searchFilter,
searchArguments,
searchCtls);
while (answer.hasMoreElements()) {
SearchResult sr = (SearchResult) answer.next();
Attributes attrs = sr.getAttributes();
if (attrs != null) {
NamingEnumeration<?> ae = attrs.getAll();
while (ae.hasMore()) {
Attribute attr = (Attribute) ae.next();
if (attr.getID().equals("cn")) {
roleNames.add((String) attr.get());
}
}
}
}
return roleNames;
} catch (Exception e) {
LOG.error("Error", e);
}
return new HashSet<>();
}

開發者ID:apache, 項目名稱:zeppelin, 代碼行數:40, 代碼來源: LdapGroupRealm.java


示例4: deleteEntityByDn


import javax.naming.ldap.LdapContext; //導入方法依賴的package包/類
public void deleteEntityByDn(String dn) {
try {
LdapContext context = connectionService.getContext();
SearchControls searchControls = new SearchControls();
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration<SearchResult> children = context.search(dn, "(objectclass=*)", searchControls);
TreeSet<String> dnsToDelete = new TreeSet<>(new DnComparator(true));
while (children.hasMoreElements()) {
SearchResult childResult = children.nextElement();
String childDn = childResult.getNameInNamespace();
dnsToDelete.add(childDn);
}
for (String s : dnsToDelete) {
context.destroySubcontext(s);
}
} catch (NamingException e) {
throw new CukesRuntimeException("Cannot delete entity by dn " + dn, e);
} finally {
connectionService.close();
}
}

開發者ID:ctco, 項目名稱:cukes, 代碼行數:22, 代碼來源: EntityService.java


示例5: searchByFilter


import javax.naming.ldap.LdapContext; //導入方法依賴的package包/類
public List<Attributes> searchByFilter(String dn, String filter){
try {
LdapContext context = connectionService.getContext();
NamingEnumeration<SearchResult> searchResults = context.search(dn, filter, new SearchControls());
List<Attributes> attributesList = new ArrayList<>();
while (searchResults.hasMore()) {
SearchResult searchResult = searchResults.next();
attributesList.add(searchResult.getAttributes());
}
return attributesList;
} catch (NamingException ex) {
throw new CukesRuntimeException(ex);
} finally {
connectionService.close();
}
}

開發者ID:ctco, 項目名稱:cukes, 代碼行數:17, 代碼來源: EntityService.java


示例6: getUserDn


import javax.naming.ldap.LdapContext; //導入方法依賴的package包/類
@Instrumentation.TraceEntry(message = "get ldap user DN for username: {{1}}", timer = "ldap")
private static @Nullable String getUserDn(LdapContext ldapContext, String username,
LdapConfig ldapConfig) throws NamingException {
SearchControls searchCtls = new SearchControls();
searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration<?> namingEnum = ldapContext.search(ldapConfig.userBaseDn(),
ldapConfig.userSearchFilter(), new String[] {username}, searchCtls);
try {
if (!namingEnum.hasMore()) {
return null;
}
SearchResult result = (SearchResult) checkNotNull(namingEnum.next());
String userDn = result.getNameInNamespace();
if (namingEnum.hasMore()) {
throw new IllegalStateException("More than matching user: " + username);
}
return userDn;
} finally {
namingEnum.close();
}
}

開發者ID:glowroot, 項目名稱:glowroot, 代碼行數:22, 代碼來源: LdapAuthentication.java


示例7: getGroupDnsForUserDn


import javax.naming.ldap.LdapContext; //導入方法依賴的package包/類
@Instrumentation.TraceEntry(message = "get ldap group DNs for user DN: {{1}}", timer = "ldap")
private static Set<String> getGroupDnsForUserDn(LdapContext ldapContext, String userDn,
LdapConfig ldapConfig) throws NamingException {
SearchControls searchCtls = new SearchControls();
searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration<?> namingEnum = ldapContext.search(ldapConfig.groupBaseDn(),
ldapConfig.groupSearchFilter(), new String[] {userDn}, searchCtls);
try {
Set<String> ldapGroups = Sets.newHashSet();
while (namingEnum.hasMore()) {
SearchResult result = (SearchResult) checkNotNull(namingEnum.next());
ldapGroups.add(result.getNameInNamespace());
}
return ldapGroups;
} finally {
namingEnum.close();
}
}

開發者ID:glowroot, 項目名稱:glowroot, 代碼行數:19, 代碼來源: LdapAuthentication.java


示例8: getUsersInGroup


import javax.naming.ldap.LdapContext; //導入方法依賴的package包/類
@Override
public List<LdapUser> getUsersInGroup(String groupName, LdapContext context, Long domainId) throws NamingException {
if (StringUtils.isBlank(groupName)) {
throw new IllegalArgumentException("ldap group name cannot be blank");
}
String basedn = _ldapConfiguration.getBaseDn(domainId);
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(domainId));
NamingEnumeration<SearchResult> results = context.search(basedn, generateADGroupSearchFilter(groupName, domainId), searchControls);
final List<LdapUser> users = new ArrayList<LdapUser>();
while (results.hasMoreElements()) {
final SearchResult result = results.nextElement();
users.add(createUser(result, domainId));
}
return users;
}

開發者ID:apache, 項目名稱:cloudstack, 代碼行數:24, 代碼來源: ADLdapUserManagerImpl.java


示例9: searchUser


import javax.naming.ldap.LdapContext; //導入方法依賴的package包/類
public LdapUser searchUser(final String basedn, final String searchString, final LdapContext context, Long domainId) throws NamingException, IOException {
final SearchControls searchControls = new SearchControls();
searchControls.setSearchScope(_ldapConfiguration.getScope());
searchControls.setReturningAttributes(_ldapConfiguration.getReturnAttributes(domainId));
NamingEnumeration<SearchResult> results = context.search(basedn, searchString, searchControls);
if(s_logger.isDebugEnabled()) {
s_logger.debug("searching user(s) with filter: \"" + searchString + "\"");
}
final List<LdapUser> users = new ArrayList<LdapUser>();
while (results.hasMoreElements()) {
final SearchResult result = results.nextElement();
users.add(createUser(result, domainId));
}
if (users.size() == 1) {
return users.get(0);
} else {
throw new NamingException("No user found for basedn " + basedn + " and searchString " + searchString);
}
}

開發者ID:apache, 項目名稱:cloudstack, 代碼行數:23, 代碼來源: OpenLdapUserManagerImpl.java


示例10: getFullyQualifiedNameByUserId


import javax.naming.ldap.LdapContext; //導入方法依賴的package包/類
protected String getFullyQualifiedNameByUserId(String userId) throws UnauthorizedOperationException {
env.put(Context.SECURITY_PRINCIPAL, ctxPrinciplePattern.replaceAll(userNamePattern, delegatedUserName));
env.put(Context.SECURITY_CREDENTIALS, delegatedUserPassword);
try {
LdapContext ctx = new InitialLdapContext(env,null);
String searchFilter = searchFilterPattern.replaceAll(userNamePattern, userId);
SearchControls searchControls = new SearchControls();
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration<SearchResult> results = ctx.search(ldapSearchBase,
searchFilter, searchControls);
SearchResult searchResult = null;
if (results.hasMoreElements()) {
searchResult = results.nextElement();
return searchResult.getNameInNamespace();
}
return null;
} catch (NamingException e) {
throw new UnauthorizedOperationException(e.getMessage());
}
}

開發者ID:ndexbio, 項目名稱:ndex-rest, 代碼行數:25, 代碼來源: LDAPAuthenticator.java


示例11: findUserDn


import javax.naming.ldap.LdapContext; //導入方法依賴的package包/類
/**
* Finds a distinguished name(DN) of a user by querying the active directory LDAP context for the
* specified username.
*/
protected String findUserDn(LdapContextFactory ldapContextFactory, String username) throws NamingException {
LdapContext ctx = null;
try {
// Binds using the system username and password.
ctx = ldapContextFactory.getSystemLdapContext();
final SearchControls ctrl = new SearchControls();
ctrl.setCountLimit(1);
ctrl.setSearchScope(SearchControls.SUBTREE_SCOPE);
ctrl.setTimeLimit(searchTimeoutMillis);
final String filter =
searchFilter != null ? USERNAME_PLACEHOLDER.matcher(searchFilter)
.replaceAll(username)
: username;
final NamingEnumeration<SearchResult> result = ctx.search(searchBase, filter, ctrl);
try {
if (!result.hasMore()) {
throw new AuthenticationException("No username: " + username);
}
return result.next().getNameInNamespace();
} finally {
result.close();
}
} finally {
LdapUtils.closeContext(ctx);
}
}

開發者ID:line, 項目名稱:centraldogma, 代碼行數:33, 代碼來源: SearchFirstActiveDirectoryRealm.java


示例12: userList


import javax.naming.ldap.LdapContext; //導入方法依賴的package包/類
public static ArrayList<String> userList()
{
loadAdmindetails();
System.out.println("Details Loaded");
Properties props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
props.put(Context.PROVIDER_URL, url);
props.put(Context.SECURITY_PRINCIPAL, "cn="+ldapadminuname+",dc=serverless,dc=com");//adminuser - User with special priviledge, dn user
props.put(Context.SECURITY_CREDENTIALS, ldapadminpassword);//dn user password
ArrayList<String> resp = new ArrayList<String>();
try {
LdapContext ctx = new InitialLdapContext(props, null);
ctx.setRequestControls(null);
NamingEnumeration<?> namingEnum = ctx.search("ou=ias,dc=serverless,dc=com", "(objectclass=posixAccount)", AuthenticationService.getSimpleSearchControls());
while (namingEnum.hasMore ()) {
SearchResult result = (SearchResult) namingEnum.next ();
Attributes attrs = result.getAttributes ();
resp.add(attrs.get("cn").toString().substring(4));
}
namingEnum.close();
} catch (Exception e) {
e.printStackTrace();
}
return resp;
}

開發者ID:hemantverma1, 項目名稱:ServerlessPlatform, 代碼行數:28, 代碼來源: AuthenticationService.java


示例13: ldapApiQuery


import javax.naming.ldap.LdapContext; //導入方法依賴的package包/類
private List<SearchResult> ldapApiQuery(String action, String name, String filter) {
String logMsg = action + " " + filter;
List<SearchResult> result = new ArrayList<SearchResult>();
try {
initLdapContext(action);
LdapContext ldapCtx = ldapContexts.get(action);
SearchControls constraints = new SearchControls();
constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration<SearchResult> en = ldapCtx.search(name, filter, constraints);
// means all nodes
if (en == null) {
loggerInfo("LDAP信息", "獲取", "結果為空", logMsg);
return Collections.emptyList();
}
if (!en.hasMoreElements()) {
loggerInfo("LDAP信息", "獲取", "結果為空", logMsg);
return Collections.emptyList();
}
while (en != null && en.hasMoreElements()) {// maybe more than one element
Object obj = en.nextElement();
if (obj instanceof SearchResult) {
SearchResult si = (SearchResult) obj;
result.add(si);
}
}
}
catch (Exception e) {
loggerError("LDAP用戶信息獲取", logMsg, e);
clearLdapContext(action);
}
if (!result.isEmpty()) {
loggerInfo("LDAP信息", "獲取", "成功", logMsg);
}
return result;
}

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


示例14: search


import javax.naming.ldap.LdapContext; //導入方法依賴的package包/類
public NamingEnumeration<SearchResult> search(final String baseDN, final String filter) throws NamingException {
SearchControls searchControls = new SearchControls();
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
LdapContext ctx = new InitialLdapContext(env, null);
NamingEnumeration<SearchResult> result = ctx.search(baseDN, filter, searchControls);
ctx.close();
return result;
}

開發者ID:klenkes74, 項目名稱:openshift-ldapsync, 代碼行數:11, 代碼來源: LdapServer.java


示例15: getUsersInGroup


import javax.naming.ldap.LdapContext; //導入方法依賴的package包/類
@Override
public List<LdapUser> getUsersInGroup(final String groupName, final LdapContext context) throws NamingException {
final String attributeName = _ldapConfiguration.getGroupUniqueMemeberAttribute();
final SearchControls controls = new SearchControls();
controls.setSearchScope(_ldapConfiguration.getScope());
controls.setReturningAttributes(new String[]{attributeName});
final NamingEnumeration<SearchResult> result = context.search(_ldapConfiguration.getBaseDn(), generateGroupSearchFilter(groupName), controls);
final List<LdapUser> users = new ArrayList<>();
//Expecting only one result which has all the users
if (result.hasMoreElements()) {
final Attribute attribute = result.nextElement().getAttributes().get(attributeName);
final NamingEnumeration<?> values = attribute.getAll();
while (values.hasMoreElements()) {
final String userdn = String.valueOf(values.nextElement());
try {
users.add(getUserForDn(userdn, context));
} catch (final NamingException e) {
s_logger.info("Userdn: " + userdn + " Not Found:: Exception message: " + e.getMessage());
}
}
}
Collections.sort(users);
return users;
}

開發者ID:MissionCriticalCloud, 項目名稱:cosmic, 代碼行數:30, 代碼來源: OpenLdapUserManagerImpl.java


示例16: getUserForDn


import javax.naming.ldap.LdapContext; //導入方法依賴的package包/類
private LdapUser getUserForDn(final String userdn, final LdapContext context) throws NamingException {
final SearchControls controls = new SearchControls();
controls.setSearchScope(_ldapConfiguration.getScope());
controls.setReturningAttributes(_ldapConfiguration.getReturnAttributes());
final NamingEnumeration<SearchResult> result = context.search(userdn, "(objectClass=" + _ldapConfiguration.getUserObject() + ")", controls);
if (result.hasMoreElements()) {
return createUser(result.nextElement());
} else {
throw new NamingException("No user found for dn " + userdn);
}
}

開發者ID:MissionCriticalCloud, 項目名稱:cosmic, 代碼行數:13, 代碼來源: OpenLdapUserManagerImpl.java


示例17: getUser


import javax.naming.ldap.LdapContext; //導入方法依賴的package包/類
public Binding getUser(long companyId, String screenName) throws Exception {
LdapContext ctx = getContext(companyId);
if (ctx == null) {
return null;
}
String baseDN = PrefsPropsUtil.getString(companyId,
PropsKeys.LDAP_BASE_DN);
Properties userMappings = getUserMappings(companyId);
StringBuilder filter = new StringBuilder();
filter.append(StringPool.OPEN_PARENTHESIS);
filter.append(userMappings.getProperty("screenName"));
filter.append(StringPool.EQUAL);
filter.append(screenName);
filter.append(StringPool.CLOSE_PARENTHESIS);
SearchControls cons = new SearchControls(SearchControls.SUBTREE_SCOPE,
1, 0, null, false, false);
NamingEnumeration<SearchResult> enu = ctx.search(baseDN,
filter.toString(), cons);
//System.out.println("TTTTTTTTT " + baseDN + " --------- " + filter.toString() + " ==== " + cons + "");
ctx.close();
if (enu.hasMoreElements()) {
Binding binding = enu.nextElement();
// System.out.println("TTTTTTTTT " + binding);
return binding;
} else {
return null;
}
}

開發者ID:openegovplatform, 項目名稱:OEPv2, 代碼行數:38, 代碼來源: ManagerLdap.java


示例18: getUser


import javax.naming.ldap.LdapContext; //導入方法依賴的package包/類
public Binding getUser(LdapContext ctx, long companyId, String screenName) throws Exception {
if (ctx == null) {
return null;
}
String baseDN = PrefsPropsUtil.getString(companyId,
PropsKeys.LDAP_BASE_DN);
Properties userMappings = getUserMappings(companyId);
StringBuilder filter = new StringBuilder();
filter.append(StringPool.OPEN_PARENTHESIS);
filter.append(userMappings.getProperty("screenName"));
filter.append(StringPool.EQUAL);
filter.append(screenName);
filter.append(StringPool.CLOSE_PARENTHESIS);
SearchControls cons = new SearchControls(SearchControls.SUBTREE_SCOPE,
1, 0, null, false, false);
NamingEnumeration<SearchResult> enu = ctx.search(baseDN,
filter.toString(), cons);
///System.out.println("TTTTTTTTT " + baseDN + " --------- " + filter.toString() + " ==== " + cons + "");
ctx.close();
if (enu.hasMoreElements()) {
Binding binding = enu.nextElement();
// System.out.println("TTTTTTTTT " + binding);
return binding;
} else {
return null;
}
}

開發者ID:openegovplatform, 項目名稱:OEPv2, 代碼行數:37, 代碼來源: EmployeeExportToLdap.java


示例19: searchForUserName


import javax.naming.ldap.LdapContext; //導入方法依賴的package包/類
public List<String> searchForUserName(String containString, LdapContext ldapContext) throws
NamingException {
List<String> userNameList = new ArrayList<>();
SearchControls searchCtls = new SearchControls();
searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
String searchFilter = "(&(objectClass=*)(userPrincipalName=*" + containString + "*))";
Object[] searchArguments = new Object[]{containString};
NamingEnumeration answer = ldapContext.search(searchBase, searchFilter, searchArguments,
searchCtls);
while (answer.hasMoreElements()) {
SearchResult sr = (SearchResult) answer.next();
if (log.isDebugEnabled()) {
log.debug("Retrieving userprincipalname names for user [" + sr.getName() + "]");
}
Attributes attrs = sr.getAttributes();
if (attrs != null) {
NamingEnumeration ae = attrs.getAll();
while (ae.hasMore()) {
Attribute attr = (Attribute) ae.next();
if (attr.getID().toLowerCase().equals("cn")) {
userNameList.addAll(LdapUtils.getAllAttributeValues(attr));
}
}
}
}
return userNameList;
}

開發者ID:apache, 項目名稱:zeppelin, 代碼行數:34, 代碼來源: ActiveDirectoryGroupRealm.java


示例20: getUserList


import javax.naming.ldap.LdapContext; //導入方法依賴的package包/類
/**
* function to extract users from LDAP
*/
public List<String> getUserList(JndiLdapRealm r, String searchText) {
List<String> userList = new ArrayList<>();
String userDnTemplate = r.getUserDnTemplate();
String userDn[] = userDnTemplate.split(",", 2);
String userDnPrefix = userDn[0].split("=")[0];
String userDnSuffix = userDn[1];
JndiLdapContextFactory CF = (JndiLdapContextFactory) r.getContextFactory();
try {
LdapContext ctx = CF.getSystemLdapContext();
SearchControls constraints = new SearchControls();
constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
String[] attrIDs = {userDnPrefix};
constraints.setReturningAttributes(attrIDs);
NamingEnumeration result = ctx.search(userDnSuffix, "(" + userDnPrefix + "=*" + searchText +
"*)", constraints);
while (result.hasMore()) {
Attributes attrs = ((SearchResult) result.next()).getAttributes();
if (attrs.get(userDnPrefix) != null) {
String currentUser = attrs.get(userDnPrefix).toString();
userList.add(currentUser.split(":")[1].trim());
}
}
} catch (Exception e) {
LOG.error("Error retrieving User list from Ldap Realm", e);
}
LOG.info("UserList: " + userList);
return userList;
}

開發者ID:apache, 項目名稱:zeppelin, 代碼行數:32, 代碼來源: GetUserList.java



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


原文出處:Java LdapContext.search方法代碼示例 - 純淨天空
冷日
(冷日)
Webmaster
  • 註冊日: 2008/2/19
  • 來自:
  • 發表數: 15771
[轉貼]AD 的 pwdLastSet 微軟時間戳轉 JAVA date

ad的pwdLastSet,微軟時間戳轉java的date

版權聲明:本文為博主原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接和本聲明。

在ad裡面用戶的密碼最後修改時間是一個long型的。用微軟的話說:the number of 100 nanosecond intervals since January 1, 1601 (UTC)

也就是是從1601年1月1日到當前時間的一個100納秒數。首先這個數去掉後四位,就變成了毫秒數。

但是因為跟java的開始計算時間不一樣,所以還不能比較。

java是從1970年1月1日00:00:00開始算。而微軟從1601年1月1日00:00:00開始算。

要為這兩個時間點中間差多少毫秒。可需要好好算一算,是不是還得算中間有多少閏年啊。

其實不用,只要舉一個例子,知道一個具體的時間,直接能算出差值的。

比如現在知道 131596092000000000 是微軟時間 2018年1月5日 的15:00:00

而在java的date裡這個日期的毫秒數是:1515135600000

兩個的差是 11644473600000。

再有微軟的時間,先砍掉後四位,在減去 11644473600000,就可以直接轉java日期了。分毫不差。

        Date date  = new Date(13159609200000L);
        Date date2  = new Date(118,0,5,15,0,0);
        System.out.println(date2);
        System.out.println(date2.getTime());
        System.out.println(13159609200000L - date2.getTime());
        System.out.println(new Date(13205468290468L - 11644473600000L));


原文出處:ad的pwdLastSet,微软时间戳转java的date_天天的博客-CSDN博客
冷日
(冷日)
Webmaster
  • 註冊日: 2008/2/19
  • 來自:
  • 發表數: 15771
[轉貼]AD 域證書申請,導入 Java 密鑰庫,實現 ldap 修改 AD 用戶密碼

AD域證書申請,導入Java密鑰庫,實現ldap修改AD用戶密碼

版權聲明:本文為博主原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接和本聲明。

環境:Windows Server 2012 R2 + Active Directory

說明:LDAP 無法直接獲取windows Active Directory 用戶密碼,需要通過一個安全的通道(SSL)。

經過三天的折騰,查閱了無數博客論壇,其中基本都是安裝AD證書服務器,或者是跳過申請導出過程(個人覺得這部分很重要,主要是卡在這裡),所以特以此博文記錄下來,幫助廣大猿兄。

以下為服務器安裝到證書導出,以及導入到Java密鑰庫。(PS:無截圖的步驟則為默認設置,不用變動。)

一、安裝AD證書

  1. 服務器管理器->儀表盤,添加角色和功能


  1. 如圖默認,點擊下一步



  1. 配置證書服務




  1. 進入證書頒發機構

二、導出證書

  1. Win+R打開運行,輸入『mmc』

  1. 添加/刪除管理單元


  1. 添加證書單元


  1. 添加完『證書』節點後,打開『個人』,『證書』,選擇要導出的證書,注意,我們剛才申請的證書時長為五年,所以注意到期時間,因為有時存在不止一個證書。

  1. 右擊需要的證書,選擇『所有任務』,『導出』,導出證書


  1. 選擇保存路徑並命名

三、AD證書導入java密鑰庫

  1. 以管理員身份打開命令行或者Windows Powershell,進入jdk目錄下

輸入命令:.\bin\keytool -importcert -keystore .\jre\lib\security\cacerts_hf -storepass

changeit -keypass changeit -alias CA -file D:\CA\hfbupt1.cer

(第一處加粗導入到密鑰庫中的文件命名,加粗路徑為ca證書路徑位置)

  1. 是否信任,輸入Y即可導入成功

AD域用戶插入和密碼修改測試代碼https://download.csdn.net/download/hc1017/10573368


原文出處:
AD域证书申请,导入Java密钥库,实现ldap修改AD用户密码_hf寒沨的博客-CSDN博客_ad证书导出
冷日
(冷日)
Webmaster
  • 註冊日: 2008/2/19
  • 來自:
  • 發表數: 15771
[轉貼]Timestamp from LDAP
Timestamp from LDAP (ActiveDirectories lastLogonTimestamp)

Question

If I get a Timestamp it's ms since Epoch
1143584229619

But in LDAP I get a value from the timestamp more like
127877417297554938

First though was maybe ms since time of '01/01/0000' or something but it does not add up that way.

Does anyone know what the timestamp maybe; and how I can convert it into something Java can use.

Thanks in advance.

--------------------------------------------------------------------------------

Answers

Hi

lastLogonTimeStamp seems to be the no of 100 nano second intervals starting from 0000 hrs 1/1/1601.

This is similiar to windows file time format and .NET has support to create a System.DateTime object out of this value.. Note the sample here, using the long value that you had provided and watch the date being recreated..

.NET Sample :
import  System.*;
class Test
{
    public static void main(String args[])

    {
    DateTime dt=DateTime.FromFileTime(127877417297554938L);
    System.out.println(dt);
    }
}


Java Sample :
If you want to create a java date object out of this value, please try following this sample, where i have used an adjustment factor to convert the lastLogonTimestamp value into a Date object..

import  java.util.*;
class Test
{
    public static void main(String args[])
    {

           long llastLogonAdjust=11644473600000L;  // adjust factor for converting it to java
                                                                                 //date Epoch
           Date lastLogon = new Date(127877417297554938L/10000-llastLogonAdjust); //
           System.out.println(lastLogon);
    }
}


Thanks

--------------------------------------------------------------------------------

All replies

Hi

lastLogonTimeStamp seems to be the no of 100 nano second intervals starting from 0000 hrs 1/1/1601.

This is similiar to windows file time format and .NET has support to create a System.DateTime object out of this value.. Note the sample here, using the long value that you had provided and watch the date being recreated..

.NET Sample :
import  System.*;
class Test
{
    public static void main(String args[])

    {
    DateTime dt=DateTime.FromFileTime(127877417297554938L);
    System.out.println(dt);
    }
}


Java Sample :
If you want to create a java date object out of this value, please try following this sample, where i have used an adjustment factor to convert the lastLogonTimestamp value into a Date object..

import  java.util.*;
class Test
{
    public static void main(String args[])
    {

           long llastLogonAdjust=11644473600000L;  // adjust factor for converting it to java
                                                                                 //date Epoch
           Date lastLogon = new Date(127877417297554938L/10000-llastLogonAdjust); //
           System.out.println(lastLogon);
    }
}


Thanks

原文出處:Timestamp from LDAP (ActiveDirectories lastLogonTimestamp)


冷日:
簡言之,就是 Windows AD 的時間不是 UnixTimestamp!
所以有一個誤差值:11644473600000L

以下是Java Ldap convert lastLogonTimestamp to DateTime - Stack Overflow提供的解答:
To convert a Win32 filetime string to Date, use:

long fileTime = (Long.parseLong(inputDateString) / 10000L) - 
11644473600000L;
Date inputDate = new Date(fileTime);


To convert a Date to Win32 filetime, use:
long fileTime = (inputDate.getTime() + 11644473600000L) * 10000L;
String outputDate = Long.toString(fileTime);


e.g. 131220409910000000 will be converted to 2016/10/27 14-23-11 and vice versa

Check this url for a nice online epoch/filetime converter:http://www.epochconverter.com/ldap

前一個主題 | 頁首 | | |



Powered by XOOPS 2.0 © 2001-2008 The XOOPS Project|