Spring Boot 2+无法自动装配。 “ UserDetailsS​​ervice”的bean不止一个

时间:2019-06-21 11:15:37

标签: spring-boot spring-mvc spring-security jwt userdetailsservice

大家好,我是spring security和jwt的新手。我在我的Spring Boot项目中实现Jwt以保护用户登录,并且我正在使用Spring Boot 2.1.5 而且我对Spring Boot 2+中的新bean限制了解不多。 我需要一些帮助..在这里,我尝试使用@Autowired UserDetailsS​​ervice,代码可以正常运行..结果也很好..但是intellij显示错误

  

@Autowired UserDetailsS​​ervice jwtUserDetailsS​​ervice

说...无法自动接线。有一个以上的UserDetailsS​​ervice类型的bean。

谁能向我解释这里发生了什么问题,为什么我不能自动接线,为什么以及在Spring Boot 2+中自动接线的限制是什么?

在此先感谢

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurity extends WebSecurityConfigurerAdapter {

    @Autowired
    private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtFilter jwtFilter;

    @Autowired
    private UserDetailsService jwtUserDetailsService; // here i got error only

    @Autowired
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(jwtUserDetailsService).passwordEncoder(passwordEncoder);
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

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

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.authorizeRequests().antMatchers("/api/user/add", "/generate").permitAll().anyRequest().authenticated().and()            .exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint)
                .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        http.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class);
    }
}

我的customUserDetailService是

@Service
public class JwtUserDetailService implements UserDetailsService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userRepository.findByUsername(username);
        if (user != null) {
            return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), new ArrayList<>());
        } else {
            throw new UsernameNotFoundException("Username does't exists");
        }

    }
}

我的JwtController类公开了休息点以生成jwt令牌


@CrossOrigin
@RestController
public class JwtController {

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private JwtUserDetailService jwtUserDetailService;

    @PostMapping(value = "/generate")
    public ResponseEntity<?> generateToken(@RequestBody JwtRequest jwtRequest) throws Exception {
        try {
            authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(jwtRequest.getUsername(),
                    jwtRequest.getPassword()));
        } catch (DisabledException e) {
            throw new Exception("USER_DISABLED", e);
        } catch (BadCredentialsException e) {
            throw new Exception("INVAILD_CREDENTIALS", e);
        }
        final UserDetails userDetails = jwtUserDetailService.loadUserByUsername(jwtRequest.getUsername());
        final String token = jwtUtils.generateToken(userDetails);

        return ResponseEntity.ok(new JwtResponse(token));
    }
}

我的JwtFilter类

@Component
public class JwtFilter extends OncePerRequestFilter {

    @Autowired
    private JwtUserDetailService jwtUserDetailService;

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {

        final String requestTokenHeader = request.getHeader("Authorization");

        String username = null;
        String jwtToken = null;

        if (requestTokenHeader != null && requestTokenHeader.startsWith("Bearer ")) {
            jwtToken = requestTokenHeader.substring(7);
            try {
                username = jwtUtils.getUsernameFromToken(jwtToken);
            } catch (IllegalArgumentException e) {
                System.out.println("Unable to get JWT Token");
            } catch (ExpiredJwtException e) {
                System.out.println("JWT Token has expired");
            }
        } else {
            logger.warn("JWT Token does not begin with Bearer String");
        }

        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {

            UserDetails userDetails = this.jwtUserDetailService.loadUserByUsername(username);

            if (jwtUtils.validate(jwtToken, userDetails)) {

                UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
                        userDetails, null, userDetails.getAuthorities());
                usernamePasswordAuthenticationToken
                        .setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
               SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
            }
        }
        chain.doFilter(request, response);
    }

}

其他与实体,存储库和一些安全的RESTEND点一样正常的东西

2 个答案:

答案 0 :(得分:0)

UserDetailsS​​ervice由spring提供。 要自动连线,您需要使用它进行配置。

@Bean
public UserDetailsService getUserDetails(){
   return new JwtUserDetailService(); // Implementation class
}

如果您对Bean配置不感兴趣。 您可以直接自动接线JwtUserDetailService。

@Autowired
private JwtUserDetailService jwtUserDetailsService;

答案 1 :(得分:0)

我在另一个上下文中遇到了相同的错误。原因是Idea不知道要使用哪种类型的UserDetailsS​​ervice的bean。 我的解决方案是通过注释 Qualifier

@Qualifier("beanNameWhichYouWantUse")
@Autowired
private UserDetailsService jwtUserDetailsService;

如果使用Idea(想法):将鼠标指向错误,请从上下文菜单中选择:

"More actions" -> "Add qualifier"

enter image description here

并最终选择bean