📄 ldapmanager.java
字号:
buf.append("\t emailField: ").append(emailField).append("\n");
buf.append("\t adminDN: ").append(adminDN).append("\n");
buf.append("\t adminPassword: ").append(adminPassword).append("\n");
buf.append("\t searchFilter: ").append(searchFilter).append("\n");
buf.append("\t subTreeSearch:").append(subTreeSearch).append("\n");
buf.append("\t ldapDebugEnabled: ").append(ldapDebugEnabled).append("\n");
buf.append("\t sslEnabled: ").append(sslEnabled).append("\n");
buf.append("\t initialContextFactory: ").append(initialContextFactory).append("\n");
buf.append("\t connectionPoolEnabled: ").append(connectionPoolEnabled).append("\n");
buf.append("\t autoFollowReferrals: ").append(followReferrals).append("\n");
buf.append("\t groupNameField: ").append(groupNameField).append("\n");
buf.append("\t groupMemberField: ").append(groupMemberField).append("\n");
buf.append("\t groupDescriptionField: ").append(groupDescriptionField).append("\n");
buf.append("\t posixMode: ").append(posixMode).append("\n");
buf.append("\t groupSearchFilter: ").append(groupSearchFilter).append("\n");
if (Log.isDebugEnabled()) {
Log.debug("LdapManager: "+buf.toString());
}
if (ldapDebugEnabled) {
System.err.println(buf.toString());
}
}
/**
* Returns a DirContext for the LDAP server that can be used to perform
* lookups and searches using the default base DN. The alternate DN will be used
* in case there is a {@link NamingException} using base DN. The context uses the
* admin login that is defined by <tt>adminDN</tt> and <tt>adminPassword</tt>.
*
* @return a connection to the LDAP server.
* @throws NamingException if there is an error making the LDAP connection.
*/
public LdapContext getContext() throws NamingException {
try {
return getContext(baseDN);
}
catch (NamingException e) {
if (alternateBaseDN != null) {
return getContext(alternateBaseDN);
} else {
throw(e);
}
}
}
/**
* Returns a DirContext for the LDAP server that can be used to perform
* lookups and searches using the specified base DN. The context uses the
* admin login that is defined by <tt>adminDN</tt> and <tt>adminPassword</tt>.
*
* @param baseDN the base DN to use for the context.
* @return a connection to the LDAP server.
* @throws NamingException if there is an error making the LDAP connection.
*/
public LdapContext getContext(String baseDN) throws NamingException {
boolean debug = Log.isDebugEnabled();
if (debug) {
Log.debug("LdapManager: Creating a DirContext in LdapManager.getContext()...");
}
// Set up the environment for creating the initial context
Hashtable<String, Object> env = new Hashtable<String, Object>();
env.put(Context.INITIAL_CONTEXT_FACTORY, initialContextFactory);
env.put(Context.PROVIDER_URL, getProviderURL(baseDN));
if (sslEnabled) {
env.put("java.naming.ldap.factory.socket",
"org.jivesoftware.util.SimpleSSLSocketFactory");
env.put(Context.SECURITY_PROTOCOL, "ssl");
}
// Use simple authentication to connect as the admin.
if (adminDN != null) {
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, adminDN);
if (adminPassword != null) {
env.put(Context.SECURITY_CREDENTIALS, adminPassword);
}
}
// No login information so attempt to use anonymous login.
else {
env.put(Context.SECURITY_AUTHENTICATION, "none");
}
if (ldapDebugEnabled) {
env.put("com.sun.jndi.ldap.trace.ber", System.err);
}
if (connectionPoolEnabled) {
env.put("com.sun.jndi.ldap.connect.pool", "true");
}
if (followReferrals) {
env.put(Context.REFERRAL, "follow");
}
if (debug) {
Log.debug("LdapManager: Created hashtable with context values, attempting to create context...");
}
// Create new initial context
LdapContext context = new InitialLdapContext(env, null);
if (debug) {
Log.debug("LdapManager: ... context created successfully, returning.");
}
return context;
}
/**
* Returns true if the user is able to successfully authenticate against
* the LDAP server. The "simple" authentication protocol is used.
*
* @param userDN the user's dn to authenticate (relative to <tt>baseDN</tt>).
* @param password the user's password.
* @return true if the user successfully authenticates.
*/
public boolean checkAuthentication(String userDN, String password) {
boolean debug = Log.isDebugEnabled();
if (debug) {
Log.debug("LdapManager: In LdapManager.checkAuthentication(userDN, password), userDN is: " + userDN + "...");
}
DirContext ctx = null;
try {
// See if the user authenticates.
Hashtable<String, Object> env = new Hashtable<String, Object>();
env.put(Context.INITIAL_CONTEXT_FACTORY, initialContextFactory);
env.put(Context.PROVIDER_URL, getProviderURL(baseDN));
if (sslEnabled) {
env.put("java.naming.ldap.factory.socket",
"org.jivesoftware.util.SimpleSSLSocketFactory");
env.put(Context.SECURITY_PROTOCOL, "ssl");
}
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, userDN + "," + baseDN);
env.put(Context.SECURITY_CREDENTIALS, password);
// Specify timeout to be 10 seconds, only on non SSL since SSL connections
// break with a timemout.
if (!sslEnabled) {
env.put("com.sun.jndi.ldap.connect.timeout", "10000");
}
if (readTimeout > 0) {
env.put("com.sun.jndi.ldap.read.timeout", String.valueOf(readTimeout));
}
if (ldapDebugEnabled) {
env.put("com.sun.jndi.ldap.trace.ber", System.err);
}
if (followReferrals) {
env.put(Context.REFERRAL, "follow");
}
if (debug) {
Log.debug("LdapManager: Created context values, attempting to create context...");
}
ctx = new InitialDirContext(env);
if (debug) {
Log.debug("LdapManager: ... context created successfully, returning.");
}
}
catch (NamingException ne) {
// If an alt baseDN is defined, attempt a lookup there.
if (alternateBaseDN != null) {
try {
if (ctx != null) {
ctx.close();
}
}
catch (Exception e) {
Log.error(e);
}
try {
// See if the user authenticates.
Hashtable<String, Object> env = new Hashtable<String, Object>();
// Use a custom initial context factory if specified. Otherwise, use the default.
env.put(Context.INITIAL_CONTEXT_FACTORY, initialContextFactory);
env.put(Context.PROVIDER_URL, getProviderURL(alternateBaseDN));
if (sslEnabled) {
env.put("java.naming.ldap.factory.socket", "org.jivesoftware.util.SimpleSSLSocketFactory");
env.put(Context.SECURITY_PROTOCOL, "ssl");
}
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, userDN + "," + alternateBaseDN);
env.put(Context.SECURITY_CREDENTIALS, password);
// Specify timeout to be 10 seconds, only on non SSL since SSL connections
// break with a timemout.
if (!sslEnabled) {
env.put("com.sun.jndi.ldap.connect.timeout", "10000");
}
if (ldapDebugEnabled) {
env.put("com.sun.jndi.ldap.trace.ber", System.err);
}
if (followReferrals) {
env.put(Context.REFERRAL, "follow");
}
if (debug) {
Log.debug("LdapManager: Created context values, attempting to create context...");
}
ctx = new InitialDirContext(env);
}
catch (NamingException e) {
if (debug) {
Log.debug("LdapManager: Caught a naming exception when creating InitialContext", ne);
}
return false;
}
}
else {
if (debug) {
Log.debug("LdapManager: Caught a naming exception when creating InitialContext", ne);
}
return false;
}
}
finally {
try {
if (ctx != null) {
ctx.close();
}
}
catch (Exception e) {
Log.error(e);
}
}
return true;
}
/**
* Finds a user's dn using their username. Normally, this search will
* be performed using the field "uid", but this can be changed by setting
* the <tt>usernameField</tt> property.<p>
*
* Searches are performed over all subtrees relative to the <tt>baseDN</tt>.
* If the search fails in the <tt>baseDN</tt> then another search will be
* performed in the <tt>alternateBaseDN</tt>. For example, if the <tt>baseDN</tt>
* is "o=jivesoftware, o=com" and we do a search for "mtucker", then we might
* find a userDN of "uid=mtucker,ou=People". This kind of searching is a good
* thing since it doesn't make the assumption that all user records are stored
* in a flat structure. However, it does add the requirement that "uid" field
* (or the other field specified) must be unique over the entire subtree from
* the <tt>baseDN</tt>. For example, it's entirely possible to create two dn's
* in your LDAP directory with the same uid: "uid=mtucker,ou=People" and
* "uid=mtucker,ou=Administrators". In such a case, it's not possible to
* uniquely identify a user, so this method will throw an error.<p>
*
* The dn that's returned is relative to the default <tt>baseDN</tt>.
*
* @param username the username to lookup the dn for.
* @return the dn associated with <tt>username</tt>.
* @throws Exception if the search for the dn fails.
*/
public String findUserDN(String username) throws Exception {
try {
return findUserDN(username, baseDN);
}
catch (Exception e) {
if (alternateBaseDN != null) {
return findUserDN(username, alternateBaseDN);
}
else {
throw e;
}
}
}
/**
* Finds a user's dn using their username in the specified baseDN. Normally, this search
* will be performed using the field "uid", but this can be changed by setting
* the <tt>usernameField</tt> property.<p>
*
* Searches are performed over all sub-trees relative to the <tt>baseDN</tt> unless
* sub-tree searching has been disabled. For example, if the <tt>baseDN</tt> is
* "o=jivesoftware, o=com" and we do a search for "mtucker", then we might find a userDN of
* "uid=mtucker,ou=People". This kind of searching is a good thing since
* it doesn't make the assumption that all user records are stored in a flat
* structure. However, it does add the requirement that "uid" field (or the
* other field specified) must be unique over the entire subtree from the
* <tt>baseDN</tt>. For example, it's entirely possible to create two dn's
* in your LDAP directory with the same uid: "uid=mtucker,ou=People" and
* "uid=mtucker,ou=Administrators". In such a case, it's not possible to
* uniquely identify a user, so this method will throw an error.<p>
*
* The DN that's returned is relative to the <tt>baseDN</tt>.
*
* @param username the username to lookup the dn for.
* @param baseDN the base DN to use for this search.
* @return the dn associated with <tt>username</tt>.
* @throws Exception if the search for the dn fails.
* @see #findUserDN(String) to search using the default baseDN and alternateBaseDN.
*/
public String findUserDN(String username, String baseDN) throws Exception {
boolean debug = Log.isDebugEnabled();
//Support for usernameSuffix
username = username + usernameSuffix;
if (debug) {
Log.debug("LdapManager: Trying to find a user's DN based on their username. " + usernameField + ": " + username
+ ", Base DN: " + baseDN + "...");
}
DirContext ctx = null;
try {
ctx = getContext(baseDN);
if (debug) {
Log.debug("LdapManager: Starting LDAP search...");
}
// Search for the dn based on the username.
SearchControls constraints = new SearchControls();
// If sub-tree searching is enabled (default is true) then search the entire tree.
if (subTreeSearch) {
constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
}
// Otherwise, only search a single level.
else {
constraints.setSearchScope(SearchControls.ONELEVEL_SCOPE);
}
constraints.setReturningAttributes(new String[] { usernameField });
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -