[英]Active Directory Using spring security
我的要求是。 我有一個具有彈簧安全性的登錄頁面。 首先我想用活動目錄驗證用戶名和密碼,如果用戶存在,那么我只需要檢查數據庫中的用戶名。
我已經在網上嘗試過使用 spring security 進行 LDAP 身份驗證。
您需要做的是注入 LdapAuthenticator 的自定義實現。 我做過類似的事情,但是在一個 3 年以來的舊項目中,您可能需要更改代碼。 基本上我們做這樣的事情(仔細閱讀評論):
import org.springframework.ldap.core.DirContextAdapter;
import org.springframework.ldap.core.DirContextOperations;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.ldap.DefaultSpringSecurityContextSource;
import org.springframework.security.ldap.authentication.LdapAuthenticator;
public class LdapAuthenticatorImpl implements LdapAuthenticator {
private DefaultSpringSecurityContextSource contextFactory;
private String principalPrefix = "";
public DirContextOperations authenticate(Authentication authentication) {
// Grab the username and password out of the authentication object.
String principal = principalPrefix + authentication.getName();
String password = "";
if (authentication.getCredentials() != null) {
password = authentication.getCredentials().toString();
}
// If we have a valid username and password, try to authenticate.
if (!("".equals(principal.trim())) && !("".equals(password.trim()))) {
InitialLdapContext ldapContext = (InitialLdapContext) contextFactory.getReadWriteContext();
//We attempt the super class authentication which will validate the credentials. In case
//of success it will return an instance of authAdapter otherwise it will throw BadCredentialsException.
DirContextOperations authAdapter = super.authenticate(authentication) ;
//We can consider authentication successful with LDAP.
//TODO check the user in the database
//
return authAdapter;
} else {
throw new BadCredentialsException("Blank username and/or password!");
}
}
}
在配置文件中,您需要使用您的實現覆蓋名為 ldapAuthenticator 的現有 bean。 以下 grails 語法示例,但您可以在 application-descriptor.xml 中執行相同操作:
ldapAuthenticator(CustomBindAuthenticator, ref('contextSource')) {
userSearch = ref('ldapUserSearch')
}
你也可以像這樣在xml中配置它:
<bean id="ldapAuthenticator" class="com.mypackage.myClass">
<constructor-arg ref="contextSource"/>
<property name="userSearch" ref="ldapUserSearch"/>
</bean>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.