当通过Spring安全ldap验证用户时,未获得任何授权的错误。

问题描述 投票:1回答:1

我正试图通过LDAP服务器使用spring boot验证用户,我已经成功地Confiured LDAP。现在,当我使用 authenticationManager()验证用户凭证时,我得到了 not granted any authorities 错误。我试了好几段代码,但没有找到合适的解决方案,也可能是我在整个认证过程中错过了一些重要的点。

控制器。

@RequestMapping(value = "/login", method = RequestMethod.POST)
//  public ResponseEntity<?> authenticateUser(@Valid @RequestBody LoginRequest loginRequest, BindingResult result){

    public ResponseEntity<?> authenticateUser(@Valid @ModelAttribute LoginRequest loginRequest, BindingResult result){
        ResponseEntity<?> errorMap = mapValidationErrorService.getMapValidationErrors(result);
        if(errorMap != null) return errorMap;
        String jwt = null;

        try {
                Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()) );
                System.out.println("test : "+authentication.toString());
                SecurityContextHolder.getContext().setAuthentication(authentication);
                jwt = TOKEN_PREFIX + tokenProvider.generateToken(authentication);
        }catch (Exception e) {
                return new ResponseEntity<>("Not Authorized", HttpStatus.FORBIDDEN);
        }

安全配置

public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Value("${ldap-url}")
    private String url;

    @Value("${ldap-basedn}")
    private String baseDn;

    @Value("${ldap-user-password}")
    private String userPassword;

    @Value("${ldap-user-dnpattern}")
    private String userDnPattern;

    @Value("${ldap.password}")
    private String ldapPrincipalPassword;

    @Value("${ldap.username}")
    private String ldapSecurityPrincipal;

    @Autowired
    private JwtAuthenticationEntryPoint unauthorizedhandler;

    @Autowired
    private CustomUserDetailsService customUserDetailsService;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Bean
    public JwtAuthenticationFilter jwtAuthenticationFilter() { return new JwtAuthenticationFilter();}

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
        .ldapAuthentication()
            .userDnPatterns(userDnPattern)
            .contextSource()
                .url(url+baseDn)
                .managerDn(ldapSecurityPrincipal)
                .managerPassword(ldapPrincipalPassword)
                .and()
                .passwordCompare()
                .passwordEncoder(new LdapShaPasswordEncoder())
                .passwordAttribute("userPassword");


//      super.configure(auth);
//      auth.userDetailsService(customUserDetailsService).passwordEncoder(bCryptPasswordEncoder);
    }


    @Override
    @Bean(BeanIds.AUTHENTICATION_MANAGER)
    protected AuthenticationManager authenticationManager() throws Exception {
        // TODO Auto-generated method stub
        return super.authenticationManager();
    }

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

        http.cors();
        http.csrf().disable()
            .exceptionHandling().authenticationEntryPoint(null).and()
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .headers().frameOptions().sameOrigin()
            .and()
            .authorizeRequests()
            .antMatchers(
                    "/",
                    "favicon.ico",
                    "/**/*.png",
                    "/**/*.gif",
                    "/**/*.svg",
                    "/**/*.jpg",
                    "/**/*.html",
                    "/**/*.css",
                    "/**/*.js"
            ).permitAll()
            .antMatchers("/api/users/**").permitAll()
            .anyRequest().fullyAuthenticated();

//          .antMatchers(SIGN_UP_URLS).permitAll()
//          .anyRequest()
//          .authenticated();


            http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);

        super.configure(http);
    }

     @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        return bCryptPasswordEncoder;
    }

}

认证结果是。

test : org.springframework.security.authentication.UsernamePasswordAuthenticationToken@58d6c26a: Principal: org.springframework.security.ldap.userdetails.LdapUserDetailsImpl@a7293dae: Dn: [email protected],ou=projectName,o=companyName; Username: [email protected]; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; CredentialsNonExpired: true; AccountNonLocked: true; Not granted any authorities; Credentials: [PROTECTED]; Authenticated: true; Details: null; Not granted any authorities

请帮我解决这个问题。如何避免not granted authorities错误.Thanks in advance!

spring-boot spring-security ldap spring-ldap spring-security-ldap
1个回答
0
投票

更新安全配置类,而不是第一配置方法(AuthenticationManagerBuilder)使用。

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {

             auth.ldapAuthentication()
             .userDnPatterns(userDnPattern)
                .contextSource()
                    .url(url+baseDn)
                    .managerDn(ldapSecurityPrincipal)
                    .managerPassword(ldapPrincipalPassword)
                    .and()
                    .ldapAuthoritiesPopulator(myAuthPopulator);
        } 

同时,自动ire LdapAuthoritiesPopulator。

© www.soinside.com 2019 - 2024. All rights reserved.