Spring Boot 应用启动失败,原因是需要一个类型为 AuthenticationManager 的 bean。

huangapple go评论114阅读模式
英文:

Spring Boot APPLICATION FAILED TO START due to required a bean of type AuthenticationManager

问题

我正在一个使用JWT的Spring Web应用程序中工作。

Spring Boot版本:3.1.0

Java版本:17

数据库:mysql

我能够成功构建。但当我尝试运行时,出现错误。

在com.myapp.controller.LoginController中,字段authenticationManager需要一个类型为'org.springframework.security.authentication.AuthenticationManager'的bean,但找不到该bean。

LoginController

  1. @Slf4j
  2. @CrossOrigin(origins = "http://localhost:8080")
  3. @RestController
  4. @RequestMapping("/api")
  5. public class LoginController {
  6. @Autowired
  7. UserRepository userRepository;
  8. @Autowired
  9. AuthenticationManager authenticationManager;
  10. @PostMapping("/login")
  11. public ResponseEntity<Object> login(@Validated(ValidationOrder.class) Login loginData,
  12. BindingResult bindingResult) {
  13. try {
  14. Optional<User> user = userRepository.findByUserEmailAddress(loginData.getUserEmailAddress());
  15. if (user.isPresent() && user.get().getUserPassword().equals(loginData.getUserPassword())) {
  16. return ResponseEntity.ok(
  17. new RestResponse(ResponseStatus.SUCCESS.toString(), "Login Success", user.get().getUserName()));
  18. } else {
  19. return ResponseEntity.ok(new RestResponse(ResponseStatus.ERROR.toString(),
  20. "Login Failed. Invalid username or password!!!", null));
  21. }
  22. } catch (Exception ex) {
  23. log.error(null, ex);
  24. return ResponseEntity.ok(new RestResponse(ResponseStatus.ERROR.toString(), ex.getMessage(), null));
  25. }
  26. }
  27. }

ApplicationSecurity

  1. @Configuration
  2. @EnableMethodSecurity
  3. public class ApplicationSecurity {
  4. @Autowired
  5. private JwtAuthenticationEntryPoint unauthorizedHandler;
  6. @Autowired
  7. JwtUserDetailsService jwtUserDetailsService;
  8. @Bean
  9. public JwtAuthenticationFilter authenticationJwtTokenFilter() {
  10. return new JwtAuthenticationFilter();
  11. }
  12. @Bean
  13. public DaoAuthenticationProvider authenticationProvider() {
  14. DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
  15. authProvider.setUserDetailsService(jwtUserDetailsService);
  16. authProvider.setPasswordEncoder(passwordEncoder());
  17. return authProvider;
  18. }
  19. @Bean
  20. public PasswordEncoder passwordEncoder() {
  21. return new BCryptPasswordEncoder();
  22. }
  23. @Bean
  24. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  25. //@formatter:off
  26. http.csrf(csrf -> csrf.disable())
  27. .exceptionHandling(exception -> exception.authenticationEntryPoint(unauthorizedHandler))
  28. .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
  29. .authorizeHttpRequests(auth -> auth.requestMatchers("/api/auth/**").permitAll()
  30. //.requestMatchers("/api/test/**").permitAll()
  31. .anyRequest()
  32. .authenticated()
  33. );
  34. //@formatter:on
  35. http.authenticationProvider(authenticationProvider());
  36. http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
  37. return http.build();
  38. }
  39. }

JwtAuthenticationEntryPoint

  1. @Component
  2. public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint, Serializable {
  3. private static final long serialVersionUID = -7858869558953243875L;
  4. @Override
  5. public void commence(HttpServletRequest request, HttpServletResponse response,
  6. AuthenticationException authException) throws IOException {
  7. response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
  8. }
  9. }

对于这个错误有什么想法?

英文:

I am working in a spring web application with JWT.

Spring Boot: 3.1.0

Java: 17

Database: mysql

I can able to build successfully. When I try to run, then getting an error

Field authenticationManager in com.myapp.controller.LoginController required a bean of type 'org.springframework.security.authentication.AuthenticationManager' that could not be found.

Spring Boot 应用启动失败,原因是需要一个类型为 AuthenticationManager 的 bean。

  1. ***************************
  2. APPLICATION FAILED TO START
  3. ***************************
  4. Description:
  5. Field authenticationManager in com.myapp.controller.LoginController required a bean of type &#39;org.springframework.security.authentication.AuthenticationManager&#39; that could not be found.
  6. The injection point has the following annotations:
  7. - @org.springframework.beans.factory.annotation.Autowired(required=true)
  8. Action:
  9. Consider defining a bean of type &#39;org.springframework.security.authentication.AuthenticationManager&#39; in your configuration.

LoginController

  1. @Slf4j
  2. @CrossOrigin(origins = &quot;http://localhost:8080&quot;)
  3. @RestController
  4. @RequestMapping(&quot;/api&quot;)
  5. public class LoginController {
  6. @Autowired
  7. UserRepository userRepository;
  8. @Autowired
  9. AuthenticationManager authenticationManager;
  10. @PostMapping(&quot;/login&quot;)
  11. public ResponseEntity&lt;Object&gt; login(@Validated(ValidationOrder.class) Login loginData,
  12. BindingResult bindingResult) {
  13. try {
  14. Optional&lt;User&gt; user = userRepository.findByUserEmailAddress(loginData.getUserEmailAddress());
  15. if (user.isPresent() &amp;&amp; user.get().getUserPassword().equals(loginData.getUserPassword())) {
  16. return ResponseEntity.ok(
  17. new RestResponse(ResponseStatus.SUCCESS.toString(), &quot;Login Success&quot;, user.get().getUserName()));
  18. } else {
  19. return ResponseEntity.ok(new RestResponse(ResponseStatus.ERROR.toString(),
  20. &quot;Login Failed. Invalid username or password!!!&quot;, null));
  21. }
  22. } catch (Exception ex) {
  23. log.error(null, ex);
  24. return ResponseEntity.ok(new RestResponse(ResponseStatus.ERROR.toString(), ex.getMessage(), null));
  25. }
  26. }
  27. }

ApplicationSecurity

  1. @Configuration
  2. @EnableMethodSecurity
  3. public class ApplicationSecurity {//extends WebSecurityConfiguration {
  4. @Autowired
  5. private JwtAuthenticationEntryPoint unauthorizedHandler;
  6. @Autowired
  7. JwtUserDetailsService jwtUserDetailsService;
  8. @Bean
  9. public JwtAuthenticationFilter authenticationJwtTokenFilter() {
  10. return new JwtAuthenticationFilter();
  11. }
  12. @Bean
  13. public DaoAuthenticationProvider authenticationProvider() {
  14. DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
  15. authProvider.setUserDetailsService(jwtUserDetailsService);
  16. authProvider.setPasswordEncoder(passwordEncoder());
  17. return authProvider;
  18. }
  19. @Bean
  20. public PasswordEncoder passwordEncoder() {
  21. return new BCryptPasswordEncoder();
  22. }
  23. @Bean
  24. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  25. //@formatter:off
  26. http.csrf(csrf -&gt; csrf.disable())
  27. .exceptionHandling(exception -&gt; exception.authenticationEntryPoint(unauthorizedHandler))
  28. .sessionManagement(session -&gt; session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
  29. .authorizeHttpRequests(auth -&gt; auth.requestMatchers(&quot;/api/auth/**&quot;).permitAll()
  30. //.requestMatchers(&quot;/api/test/**&quot;).permitAll()
  31. .anyRequest()
  32. .authenticated()
  33. );
  34. //@formatter:on
  35. http.authenticationProvider(authenticationProvider());
  36. http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
  37. return http.build();
  38. }
  39. }

JwtAuthenticationEntryPoint

  1. @Component
  2. public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint, Serializable {
  3. private static final long serialVersionUID = -7858869558953243875L;
  4. @Override
  5. public void commence(HttpServletRequest request, HttpServletResponse response,
  6. AuthenticationException authException) throws IOException {
  7. response.sendError(HttpServletResponse.SC_UNAUTHORIZED, &quot;Unauthorized&quot;);
  8. }
  9. }

Any idea about this error.

答案1

得分: 1

只需在你的 ApplicationSecurity 中添加一个 bean。
全局身份验证管理器 是什么?

  1. @Bean
  2. public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
  3. return authenticationConfiguration.getAuthenticationManager();
  4. }

最终它会起作用。

英文:

just add a bean in your ApplicationSecurity
what is
Global AuthenticationManager

  1. @Bean public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {return authenticationConfiguration.getAuthenticationManager();}

Finally it will work.

huangapple
  • 本文由 发表于 2023年7月14日 02:11:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/76682194.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定