Page 2 of 2 FirstFirst 12
Results 11 to 17 of 17

Thread: Can't do ldap bind authentication with domain\firstname.lastname

  1. #11
    Join Date
    Jul 2008
    Location
    Washington DC
    Posts
    67

    Default

    David you are exactly right on the money.

    We want to authenticate with DOMAIN\username against our federated AD. What is also a complication is that samaccountname is not the actual user name. In fact, there's really no field in this AD that has the username property directly for all users (since this AD has trusts with several other domains). As you say, I can bind with DOMAIN\username against our AD with JXPlorer or Softerra ldap browser or ldp.exe.

    How do you think we should attack this? I'm thinking in BindAuthenticator, we really can't use that bindWithDn method. I'd rather stay within the framework of what springsec provides, because the URL security and security tags are really nice and easy for configuring the rest of security within the app.

    Also, we dont need to do authorization with AD. We have Role and other user info available via an internal restful web service (I'm using RestTemplate to get roles based on the username, as I have my own authorities populator class).

    So right now, I just need Spring Security to bind with "DOMAIN\username" and password against our ldap server (Active Directory). Plain and simple. Can't use anonymous login, and can't use a manager dn to do lookups.

  2. #12

    Default any resolution?

    I am facing the exact same issue with attempting to bind against AD with domain\username. I have a similar config, but have tried everything, from simple ldap-server and auth-manager to full-blown explicit bean config, and nothing... So, would love to know if your issue was ever resolved?

  3. #13
    Join Date
    Jan 2010
    Posts
    14

    Default

    Anyone figured a easy way for this?

    I feel this page http://static.springsource.org/sprin...iguration.html has some information but not sure if this works or this other way is the way to go:
    http://www.gigaspaces.com/wiki/displ...DAP+repository

  4. #14
    Join Date
    Jan 2009
    Posts
    9

    Default

    This should be included in the Spring Security documentation.

    I culled various bits of information from google searches and came up with the following working solution using Spring 3.0.3, Spring LDAP 1.3.1 and Spring Security 3.0.5.

    applicationContext.xml
    Code:
    	<security:ldap-server id="adServer" 
    		url="${security.authentication.ldap.server.url}"/>
    	
    	<security:authentication-manager alias="authenticationManager">
    		<security:authentication-provider ref="adAuthProvider"/>
    		<security:authentication-provider ref="anonymousAuthenticationProvider"/>
    	</security:authentication-manager>
    	
    	<bean id="userContextMapper" class="com.blah.app.services.security.AdUserContextMapper"/>
    
    	
    	<bean id="adAuthenticator" class="com.blah.app.services.security.AdAuthenticator">
        	<property name="contextFactory" ref="adServer" />
            <property name="principalPrefix" value="" />
    	</bean>
    
    	<bean id="adAuthProvider" class="org.springframework.security.ldap.authentication.LdapAuthenticationProvider">  
    	    <constructor-arg ref="adAuthenticator"/>  
    	    <property name="userDetailsContextMapper" ref="userContextMapper"/>  
    	</bean>
    AdAuthenticator.java
    Code:
    public class AdAuthenticator 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())))
            {
                _contextFactory.setPassword(password);
                _contextFactory.setUserDn(principal);
                
                InitialLdapContext ldapContext = (InitialLdapContext) _contextFactory.getReadWriteContext();
                
                // We need to pass the context back out, so that the auth provider
                // can add it to the
                // Authentication object.
                DirContextOperations authAdapter = new DirContextAdapter();
                authAdapter.addAttributeValue("ldapContext", ldapContext);
    
                return authAdapter;
            }
            else
            {
                throw new BadCredentialsException("Blank username and/or password!");
            }
        }
    
        public DefaultSpringSecurityContextSource getContextFactory() 
        {
            return _contextFactory;
        }
    
        /**
         * Set the context factory to use for generating a new LDAP context.
         * 
         * @param contextFactory
         */
        public void setContextFactory(DefaultSpringSecurityContextSource contextFactory) 
        {
            _contextFactory = contextFactory;
        }
    
        public String getPrincipalPrefix() 
        {
            return _principalPrefix;
        }
    
        /**
         * Set the string to be prepended to all principal names prior to attempting authentication
         * against the LDAP server.  (For example, if the Active Directory wants the domain-name-plus
         * backslash prepended, use this.)
         * 
         * @param principalPrefix
         */
        public void setPrincipalPrefix(String principalPrefix) 
        {
            if(principalPrefix != null) 
            {
                _principalPrefix = principalPrefix;
            } 
            else 
            {
                _principalPrefix = "";
            }
        }
    }
    AdUserContextMapper.java
    Code:
    public class AdUserContextMapper implements UserDetailsContextMapper
    {
        private static Log log = LogFactory.getLog(AdUserContextMapper.class);
    
        
        @Override
        public UserDetails mapUserFromContext(DirContextOperations p_dirContext, String p_userName, Collection<GrantedAuthority> p_authorities)
        {
            String userName;
            String displayName = "";
            String mail = "";
            
            int index = 0;
            
            if( (index = p_userName.indexOf("\\")) != -1 )
                userName = p_userName.substring(index+1);
            else if( (index = p_userName.indexOf("@") ) != -1 )
                userName = p_userName.substring(0, index);
            else
                userName = p_userName;
            
            InitialLdapContext ldapContext = (InitialLdapContext)p_dirContext.getObjectAttribute("ldapContext");
            
            String returnedAtts[] ={ "displayName", "mail" };
            SearchControls sc = new SearchControls();
            sc.setReturningAttributes(returnedAtts);
            sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
            
            try
            {
                NamingEnumeration<SearchResult> result = ldapContext.search("", "(&(objectclass=user)(sAMAccountName=" + userName + "))", sc);
                
                if( result.hasMoreElements() )
                {
                    SearchResult sr = result.nextElement();
                    
                    Attributes attributes = sr.getAttributes();
                    
                    Attribute displayNameAttr = attributes.get("displayName");
                    Attribute mailAttr = attributes.get("mail");
                    
                    if( displayNameAttr != null )
                        displayName = (String)displayNameAttr.get();
                    
                    if( mailAttr != null )
                        mail = (String)mailAttr.get();
                }
            }
            catch(Throwable e)
            {
                throw new RuntimeException("Failed to retrieve user attributes from ldap server. See wrapped exception for details.", e);
            }
            finally
            {
                 LdapUtils.closeContext(ldapContext);
            }
    
            Principal principal = new Principal();
    
            principal.setUserName(p_userName);
            principal.setUserFullName(displayName);
            principal.setEmailAddress(mail);
    
    // fetch your granted authorities and set them here if they are
    // not based on AD group membership.
    //      principal.setGrantedAuthorities(new GrantedAuthority[]{"ROLE_USER"});
    
            return principal;
        }
    
        @Override
        public void mapUserToContext(UserDetails p_userDetails, DirContextAdapter p_dirContext)
        {
        }
    
    }
    I found AD would authenticate both <domain>\<username> and <username>@<dotted.domain.name.com>
    Last edited by rshan; May 13th, 2011 at 11:29 AM. Reason: Corrected code example

  5. #15
    Join Date
    Sep 2011
    Posts
    3

    Default

    Hi ,

    I tried to use the same code above, can you pl. let me know the imports for the classes. I am also facing the same issue for last 2 days.

  6. #16
    Join Date
    Jan 2009
    Posts
    9

    Default

    Quote Originally Posted by satcal View Post
    Hi ,

    I tried to use the same code above, can you pl. let me know the imports for the classes. I am also facing the same issue for last 2 days.
    AdAuthenticator:

    import javax.naming.NamingEnumeration;
    import javax.naming.directory.SearchControls;
    import javax.naming.directory.SearchResult;
    import javax.naming.ldap.InitialLdapContext;

    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    import org.springframework.ldap.CommunicationException;
    import org.springframework.ldap.core.DirContextAdapter;
    import org.springframework.ldap.core.DirContextOperations ;
    import org.springframework.ldap.support.LdapUtils;
    import org.springframework.security.authentication.BadCre dentialsException;
    import org.springframework.security.core.Authentication;
    import org.springframework.security.ldap.DefaultSpringSec urityContextSource;
    import org.springframework.security.ldap.authentication.L dapAuthenticator;

    AdUserContextMapper:

    import javax.naming.NamingEnumeration;
    import javax.naming.directory.Attribute;
    import javax.naming.directory.Attributes;
    import javax.naming.directory.SearchControls;
    import javax.naming.directory.SearchResult;
    import javax.naming.ldap.InitialLdapContext;

    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    import org.springframework.ldap.core.DirContextAdapter;
    import org.springframework.ldap.core.DirContextOperations ;
    import org.springframework.security.core.GrantedAuthority ;
    import org.springframework.security.core.authority.Grante dAuthorityImpl;
    import org.springframework.security.core.userdetails.User Details;
    import org.springframework.security.ldap.LdapUtils;
    import org.springframework.security.ldap.userdetails.User DetailsContextMapper;
    import com.foo.security.Principal;

    Principal implements org.springframework.security.core.userdetails.User Details.

  7. #17
    Join Date
    Dec 2012
    Posts
    1

    Exclamation

    Quote Originally Posted by rshan View Post
    AdAuthenticator:

    import javax.naming.NamingEnumeration;
    import javax.naming.directory.SearchControls;
    import javax.naming.directory.SearchResult;
    import javax.naming.ldap.InitialLdapContext;

    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    import org.springframework.ldap.CommunicationException;
    import org.springframework.ldap.core.DirContextAdapter;
    import org.springframework.ldap.core.DirContextOperations ;
    import org.springframework.ldap.support.LdapUtils;
    import org.springframework.security.authentication.BadCre dentialsException;
    import org.springframework.security.core.Authentication;
    import org.springframework.security.ldap.DefaultSpringSec urityContextSource;
    import org.springframework.security.ldap.authentication.L dapAuthenticator;

    AdUserContextMapper:

    import javax.naming.NamingEnumeration;
    import javax.naming.directory.Attribute;
    import javax.naming.directory.Attributes;
    import javax.naming.directory.SearchControls;
    import javax.naming.directory.SearchResult;
    import javax.naming.ldap.InitialLdapContext;

    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    import org.springframework.ldap.core.DirContextAdapter;
    import org.springframework.ldap.core.DirContextOperations ;
    import org.springframework.security.core.GrantedAuthority ;
    import org.springframework.security.core.authority.Grante dAuthorityImpl;
    import org.springframework.security.core.userdetails.User Details;
    import org.springframework.security.ldap.LdapUtils;
    import org.springframework.security.ldap.userdetails.User DetailsContextMapper;
    import com.foo.security.Principal;

    Principal implements org.springframework.security.core.userdetails.User Details.
    Hi, I am facing the same issue as above using Spring security 3.0.5 with Ldap AD. Is the issue resolved with above custom code? if so, what's the Principal code you are using ?
    Thanks.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •