[Fix-10274]Close InitialLDAPContext In LDAP (#10532)

* add finally close ctx in ldap log

* fix code style
This commit is contained in:
旺阳 2022-06-22 14:34:41 +08:00 committed by GitHub
parent f46faa02c3
commit 559f387e66
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -87,9 +87,10 @@ public class LdapService {
*/
public String ldapLogin(String userId, String userPwd) {
Properties searchEnv = getManagerLdapEnv();
LdapContext ctx = null;
try {
//Connect to the LDAP server and Authenticate with a service user of whom we know the DN and credentials
LdapContext ctx = new InitialLdapContext(searchEnv, null);
ctx = new InitialLdapContext(searchEnv, null);
SearchControls sc = new SearchControls();
sc.setReturningAttributes(new String[]{ldapEmailAttribute});
sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
@ -99,7 +100,7 @@ public class LdapService {
if (results.hasMore()) {
// get the users DN (distinguishedName) from the result
SearchResult result = results.next();
NamingEnumeration attrs = result.getAttributes().getAll();
NamingEnumeration<? extends Attribute> attrs = result.getAttributes().getAll();
while (attrs.hasMore()) {
//Open another connection to the LDAP server with the found DN and the password
searchEnv.put(Context.SECURITY_PRINCIPAL, result.getNameInNamespace());
@ -110,7 +111,7 @@ public class LdapService {
logger.warn("invalid ldap credentials or ldap search error", e);
return null;
}
Attribute attr = (Attribute) attrs.next();
Attribute attr = attrs.next();
if (attr.getID().equals(ldapEmailAttribute)) {
return (String) attr.get();
}
@ -119,7 +120,16 @@ public class LdapService {
} catch (NamingException e) {
logger.error("ldap search error", e);
return null;
} finally {
try {
if (ctx != null) {
ctx.close();
}
} catch (NamingException e) {
logger.error("ldap context close error", e);
}
}
return null;
}
@ -137,7 +147,7 @@ public class LdapService {
return env;
}
public LdapUserNotExistActionType getLdapUserNotExistAction(){
public LdapUserNotExistActionType getLdapUserNotExistAction() {
if (StringUtils.isBlank(ldapUserNotExistAction)) {
logger.info("security.authentication.ldap.user.not.exist.action configuration is empty, the default value 'CREATE'");
return LdapUserNotExistActionType.CREATE;
@ -146,7 +156,7 @@ public class LdapService {
return LdapUserNotExistActionType.valueOf(ldapUserNotExistAction);
}
public boolean createIfUserNotExists(){
public boolean createIfUserNotExists() {
return getLdapUserNotExistAction() == LdapUserNotExistActionType.CREATE;
}
}