2015-09-05 133 views
-1

我的要求是。我有一個具有彈簧安全性的登錄頁面。首先我想驗證活動目錄的用戶名和密碼,如果用戶存在,那麼我需要檢查數據庫中的用戶名。活動目錄使用彈簧安全

我一直在使用彈簧安全在線試了LDAP身份驗證..但我不能夠準確地找到如何實現這個..可以在這個任何機構幫助..

+0

什麼是您當前的問題碼?具體並給出細節。 – hoijui

+0

其實我沒有任何驗證ActiveDirectory用戶使用春季安全的代碼..你可以幫助這個 –

回答

1

你需要做的是注入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!"); 
      } 
    } 
} 

在您需要使用您的實現覆蓋現有的bean稱爲ldapAuthenticator配置文件。 Grails的語法下面的例子,但你可以做相同的應用程序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> 
+0

不清楚..你能給我如何在spring-security.xml文件中配置 –

+0

請檢查更新 –

+0

好吧..我的實際請求是用戶登錄應用程序時,首先我們需要在Active Directory中檢查天氣輸入的用戶名和密碼,如果用戶存在,則檢查天氣用戶是否存在於數據庫中,或者不是通過用戶名而是用密碼。如果用戶不在Active目錄中,我們需要引發在AD中找不到的錯誤用戶。如果用戶不存在於數據庫中,我們需要引發數據庫中找不到的錯誤用戶 –