0

Использование Spring Security 3.2 Я настроил ActiveDirectoryLdapAuthenticationProvider. Я могу аутентификацию с использованием полного имени примера [email protected], но при попытке аутентификации только с именем «Sharon» Я получаю ошибку нижеSpring Security Active Directory LDAP Authentication без полного имени

2015-12-21_17:07:00.752 DEBUG o.s.s.l.a.a.ActiveDirectoryLdapAuthenticationProvider - authenticate - Processing authentication request for user: sharon 
    2015-12-21_17:07:00.793 DEBUG o.s.s.l.SpringSecurityLdapTemplate - searchForSingleEntryInternal - Searching for entry under DN '', base = 'dc=mydomain,dc=com', filter = '(&(objectClass=user)(userPrincipalName={0}))' 
    2015-12-21_17:07:00.793 INFO o.s.s.l.SpringSecurityLdapTemplate - searchForSingleEntryInternal - Ignoring PartialResultException 
    2015-12-21_17:07:00.794 DEBUG o.s.s.l.a.LdapAuthenticationProvider - authenticate - Processing authentication request for user: gdcadmin 
    2015-12-21_17:07:00.796 DEBUG o.s.s.l.a.BindAuthenticator - bindWithDn - Attempting to bind as cn=gdcadmin,cn=Users,dc=mydomain,dc=com,dc=springframework,dc=org 
    2015-12-21_17:07:00.796 DEBUG o.s.s.l.DefaultSpringSecurityContextSource - setupEnvironment - Removing pooling flag for user cn=gdcadmin,cn=Users,dc=mydomain,dc=com,dc=springframework,dc=org 
    2015-12-21_17:07:00.858 DEBUG o.a.m.f.codec.ProtocolCodecFilter - messageReceived - Processing a MESSAGE_RECEIVED for session 1 
    2015-12-21_17:07:00.859 DEBUG o.a.d.shared.asn1.ber.Asn1Decoder - decode - >>>========================================== 
..... 
..... 
..... 
015-12-21_17:07:00.905 DEBUG o.s.s.l.a.BindAuthenticator - handleBindException - Failed to bind as cn=gdcadmin,CN=Users,DC=mydomain,DC=com: org.springframework.ldap.AuthenticationException: [LDAP: error code 49 - cannot bind the principalDn.]; nested exception is javax.naming.AuthenticationException: [LDAP: error code 49 - cannot bind the principalDn.] 

В соответствии с документом безопасности пружинным:

пользователь с именем «Шарон», например, будет затем иметь возможность проверить подлинность , введя либо имя пользователя Sharon или полный каталог UserPrincipalName Активный, а именно [email protected]

моя конфигурация

@Autowired 
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { 
     auth.authenticationProvider(activeDirectoryLdapAuthenticationProvider()); 
     auth.eraseCredentials(false); 
     auth.ldapAuthentication().userDnPatterns("cn={0},CN=Users,DC=mydomain,DC=com"); 
    } 

    @Bean 
    public ActiveDirectoryLdapAuthenticationProvider activeDirectoryLdapAuthenticationProvider() { 
     ActiveDirectoryLdapAuthenticationProvider provider = new ActiveDirectoryLdapAuthenticationProvider(env.getProperty("mydomain.com"), 
       env.getProperty("ldap://hmidir01.mydomain.com:389/")); 
     provider.setConvertSubErrorCodesToExceptions(true); 
     provider.setUseAuthenticationRequestCredentials(true); 
     provider.setUserDetailsContextMapper(userDetailsContextMapper); 
     return provider; 
    } 

Какая ошибка в моей конфигурации.

ответ

0

Вы можете реализовать в заданных способов :

1) Без сохраняющиеся данные в нашу базу данных

WebSecurityConfig .Java

@Configuration 
@EnableWebMvcSecurity 
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 

    @Bean 
    public ActiveDirectoryLdapAuthenticationProvider activeDirectoryLdapAuthenticationProvider() { 
     ActiveDirectoryLdapAuthenticationProvider provider = new ActiveDirectoryLdapAuthenticationProvider(<ldap-domain>,<ldap-url>); 
      provider.setConvertSubErrorCodesToExceptions(true); 
      provider.setUseAuthenticationRequestCredentials(true); 
     return provider; 
    } 

    @Bean 
    public LoggerListener loggerListener() { 
     return new LoggerListener(); 
    } 


    @Override 
    protected void configure(AuthenticationManagerBuilder auth) throws Exception { 
     auth.authenticationProvider(activeDirectoryLdapAuthenticationProvider()); 
    } 

    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
     http 
     .authorizeRequests() 
      .antMatchers("/admin/**").hasAnyAuthority("ADMIN") 
      .antMatchers("/user/**").hasAnyAuthority("ADMIN", "USER") 
      .antMatchers("/rest/**", "/css/**", "/fonts/**", "/images/**", "/js/**").permitAll() 
      .anyRequest().authenticated() 
     .and() 
      .formLogin() 
      .loginPage("/").failureUrl("/?error").successHandler("/home").permitAll() 
      .usernameParameter("emailId").passwordParameter("password") 
     .and() 
      .logout() 
      .logoutUrl("/logout").logoutSuccessUrl("/").permitAll() 
     .and() 
      .exceptionHandling().accessDeniedPage("/home") 
     .and() 
      .csrf() 
     .and() 
      .httpBasic();  
    } 
} 

2) При сохраняющихся данных в нашей базе

WebSecurityConfig.java

@Configuration 
@EnableWebMvcSecurity 
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 

    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
     http 
     .authorizeRequests() 
      .antMatchers("/admin/**").hasAnyAuthority("ADMIN") 
      .antMatchers("/user/**").hasAnyAuthority("ADMIN", "USER") 
      .antMatchers("/rest/**", "/css/**", "/fonts/**", "/images/**", "/js/**").permitAll() 
      .anyRequest().authenticated() 
     .and() 
      .formLogin() 
      .loginPage("/").failureUrl("/?error").successHandler("/home").permitAll() 
      .usernameParameter("emailId").passwordParameter("password") 
     .and() 
      .logout() 
      .logoutUrl("/logout").logoutSuccessUrl("/").permitAll() 
     .and() 
      .exceptionHandling().accessDeniedPage("/home") 
     .and() 
      .csrf() 
     .and() 
      .httpBasic(); 
    } 

    @Autowired 
    public void configureGlobal(AuthenticationManagerBuilder auth)throws Exception { 
     auth 
    .authenticationProvider(activeDirectoryLdapAuthenticationProvider()); 
    } 

    @Bean 
    public ActiveDirectoryLdapAuthenticationProvider activeDirectoryLdapAuthenticationProvider() { 
     ActiveDirectoryLdapAuthenticationProvider provider = new ActiveDirectoryLdapAuthenticationProvider(<ldap-domain>(null), <ldap-url>); 
     provider.setConvertSubErrorCodesToExceptions(true); 
     provider.setUseAuthenticationRequestCredentials(true); 
     provider.setUserDetailsContextMapper(userDetailsContextMapper()); 
     return provider; 
    } 

    @Bean 
    public UserDetailsContextMapper userDetailsContextMapper() { 
     return new AttributesLDAPUserDetailsContextMapper(); 
    } 
} 

AttributesLDAPUserDetailsContextMapper.java

public class AttributesLDAPUserDetailsContextMapper implements UserDetailsContextMapper { 


     @Autowired 
     private UserService service; 

     private InetOrgPersonContextMapper ldapUserDetailsMapper = new InetOrgPersonContextMapper(); 

     @Override 
     public UserDetails mapUserFromContext(DirContextOperations dirContextOperations, String userName, Collection<? extends GrantedAuthority> collection) { 

      InetOrgPerson userLdap = (InetOrgPerson) ldapUserDetailsMapper.mapUserFromContext(dirContextOperations, userName, collection); 

      User user = service.findOne(userLdap.getUsername()); 
      if (user == null) { 
       user = new Usere(); 
       user.setName(StringUtils.defaultString(userLdap.getDisplayName()).trim()); 
       user.setEmailId(StringUtils.defaultString(userLdap.getUsername()).trim()); 
       user.setdescription(StringUtils.defaultString(userLdap.getDescription()).trim()); 
       user.setIsAdmin(false); 
       user.setIsEmployee(true); 
       service.save(user); 
      } 
      return new LdapSecuredUser(user); 
     } 

     @Override 
     public void mapUserToContext(UserDetails userDetails, DirContextAdapter dirContextAdapter) { 
      ldapUserDetailsMapper.mapUserToContext(userDetails, dirContextAdapter); 
     } 
    } 

LdapSecuredUser.java

public class LdapSecuredUser extends User implements LdapUserDetails { 

    private static final long serialVersionUID = -8997460180274787521L; 

    public LdapSecuredUser(User user) { 
     if (user != null) { 
      this.setId(user.getId()); 
      this.setEmailId(user.getEmailId()); 
      this.setName(user.getName()); 
      this.setdescription(user.getDescription()); 
      this.setIsAdmin(user.getIsAdmin()); 
      this.setIsEmployee(user.getIsEmployee()); 
     } 
    } 

    @Override 
    public Collection<? extends GrantedAuthority> getAuthorities() { 
     Collection<GrantedAuthority> authorities = new ArrayList<>(); 
     authorities.add(new SimpleGrantedAuthority("USER")); 
     if(super.getIsAdmin()) 
      authorities.add(new SimpleGrantedAuthority("ADMIN")); 
     return authorities; 
    } 


    @Override 
    public String getUsername() { 
     return super.getEmailId(); 
    } 

    @Override 
    public String getPassword() { 
     return null; 
    } 

    @Override 
    public String getDn() { 
     return null; 
    } 

    @Override 
    public boolean isAccountNonExpired() { 
     return false; 
    } 

    @Override 
    public boolean isAccountNonLocked() { 
     return false; 
    } 

    @Override 
    public boolean isCredentialsNonExpired() { 
     return false; 
    } 

    @Override 
    public boolean isEnabled() { 
     return false; 
    } 

} 
+0

Можете ли вы объяснить. Я не вижу разницы между вашим кодом и моим. Мое требование - аутентифицироваться с именем пользователя, а не по электронной почте/полным именем пользователя. – Mukun

Смежные вопросы