没有LDAP密码的Spring安全性

时间:2018-10-04 13:29:08

标签: java spring-security ldap spring-ldap

我想实现具有弹簧安全性且没有任何密码的LDAP登录和搜索用户。我尝试了很多但没有运气,我使用了ActiveDirectoryLdapAuthenticationProvider DirContextOperations但没有运气,现在我正在使用密码进行操作:

登录代码:

@Configuration
@EnableWebSecurity
@PropertySource("classpath:/application.properties")
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private AppUserDetailService userDetailService;

    /*@Autowired
    private ActiveDirectoryLdapAuthenticationProvider a;*/

    private Logger logger = Logger.getLogger(WebSecurityConfig.class);

    @Value("${spring.ldap.userDnPatterns}")
    private String userDnPatterns;

    @Value("${spring.ldap.ldapUrl}")
    private String ldapUrl;

    @Value("${spring.ldap.managerDn}")
    private String managerDn;

    @Value("${spring.ldap.managerPassword}")
    private String managerPassword;

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {

        try{
        //auth.authenticationProvider(a).userDetailsService(userDetailsService());

        auth.userDetailsService(userDetailService);

        auth.ldapAuthentication().userSearchFilter(userDnPatterns).contextSource()
        .url(ldapUrl)
        .managerDn(managerDn).managerPassword(managerPassword);

        }catch(Exception e){
            logger.error("erorr connecting LDAP" + e);
        }
    }

    @Override
      protected void configure(HttpSecurity http) throws Exception {


    //   Collection<? extends GrantedAuthority> userName= SecurityContextHolder.getContext().getAuthentication().getAuthorities();

        http.cors().and().csrf().disable().authorizeRequests()
            .antMatchers("/").permitAll()
            .antMatchers("/swagger-ui.html").permitAll()   // only to test swagger
            .antMatchers(HttpMethod.POST,"/multipleSave").permitAll()  // only to test file upload from UI /savefile
            .antMatchers("/index.jsp").permitAll()
            .antMatchers("/dist/**").permitAll()// only to test file upload from UI /savefile
            .antMatchers("/lib/**").permitAll()
            .antMatchers("/css/**").permitAll()
            .antMatchers("/webjars/**").permitAll()
            .antMatchers("/images/**").permitAll()
            .antMatchers("/configuration/**").permitAll()
            .antMatchers("/swagger-resources/**").permitAll()
            .antMatchers("/v2/**").permitAll()
            .antMatchers(HttpMethod.POST, "/login").permitAll()
           // .antMatchers("/users").hasAnyAuthority("ADMIN")
            //.antMatchers("/updateGroup").hasAnyAuthority("GROUPADMIN")
           // .antMatchers("/groups").hasAnyAuthority("GROUPADMIN")
            .antMatchers("/**").permitAll()
           // .anyRequest().authenticated()
            .and()
            // We filter the api/login requests
            .addFilterBefore(new JWTLoginFilter("/login", authenticationManager()),
                    UsernamePasswordAuthenticationFilter.class)
            // And filter other requests to check the presence of JWT in header
            .addFilterBefore(new JWTAuthenticationFilter(userDetailService),
                    UsernamePasswordAuthenticationFilter.class).exceptionHandling().accessDeniedPage("/403");

      }

}

AppUserDetailService.java

@Component
public class AppUserDetailService implements UserDetailsService {

    @Autowired
    private UserDAO userRepository;

    private Logger logger = Logger.getLogger(AppUserDetailService.class);

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        com.reminder.model.User user = userRepository.getUserByName(username);
        if (user == null) {
             //userRepository.updateUnSuccessLoginDate(user.getUserId());
            throw new UsernameNotFoundException("User '" + username + "' not found");
        }
        if(!user.getActive()){

            throw new UserInactiveException("User '" + username + "' Inactive");
        }

        userRepository.updateLoginDate(user.getUserId());

        List<GrantedAuthority> authorities = new ArrayList<>();

        if(user.getGroupAdmin()!=null && user.getGroupAdmin() ){
            authorities.add(new SimpleGrantedAuthority("GROUPADMIN"));
        }


        if(user.getUserAdmin()!=null && user.getUserAdmin() ){
            authorities.add(new SimpleGrantedAuthority("ADMIN"));
        }
        UserDetails u = org.springframework.security.core.userdetails.User
        .withUsername(username)
        .password("")
        .authorities(authorities)
        .accountExpired(false)
        .accountLocked(false)
        .credentialsExpired(false)
        .disabled(false)
        .build();

        final UsernamePasswordAuthenticationToken authentication =
                new UsernamePasswordAuthenticationToken(user, null, u.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authentication);

        return u;

    }



    private List<GrantedAuthority> getGrantedAuthorities( List<GrantedAuthority> authorities) {
            authorities.add(new SimpleGrantedAuthority("ADMIN"));
        return authorities;
    }


}
ldap搜索用户的

代码:

public LdapUser getUserByUsername(String userName) {
        List<LdapUser> list = ldapTemplate.search(
                 query()
                 .attributes("cn","mail")
                 .where("objectclass").is("person").and("CN").is(userName),
                  new UserAttributesMapper());
        if (list != null && !list.isEmpty()) {
            return list.get(0);
        }
        return null;
    }

LdapTemplet在xml中定义:

<bean id="contextSource" class="org.springframework.ldap.core.support.LdapContextSource">

        <property name="url" value="ldap://localhost:389/dc=psa365,dc=com" />
        <property name="userDn" value="cn=admin,dc=test,dc=com" />
        <property name="password" value="password" />

    </bean>

    <bean id="ldapTemplate" class="org.springframework.ldap.core.LdapTemplate">
        <constructor-arg ref="contextSource" />
    </bean>

期望:我想在不使用密码的情况下实现以上目的。

0 个答案:

没有答案