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

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

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

@Slf4j
@CrossOrigin(origins = "http://localhost:8080")
@RestController
@RequestMapping("/api")
public class LoginController {

    @Autowired
    UserRepository userRepository;

    @Autowired
    AuthenticationManager authenticationManager;

    @PostMapping("/login")
    public ResponseEntity<Object> login(@Validated(ValidationOrder.class) Login loginData,
            BindingResult bindingResult) {

        try {

            Optional<User> user = userRepository.findByUserEmailAddress(loginData.getUserEmailAddress());

            if (user.isPresent() && user.get().getUserPassword().equals(loginData.getUserPassword())) {

                return ResponseEntity.ok(
                        new RestResponse(ResponseStatus.SUCCESS.toString(), "Login Success", user.get().getUserName()));

            } else {

                return ResponseEntity.ok(new RestResponse(ResponseStatus.ERROR.toString(),
                        "Login Failed. Invalid username or password!!!", null));
            }

        } catch (Exception ex) {

            log.error(null, ex);
            return ResponseEntity.ok(new RestResponse(ResponseStatus.ERROR.toString(), ex.getMessage(), null));
        }
    }
}

ApplicationSecurity

@Configuration
@EnableMethodSecurity
public class ApplicationSecurity {

    @Autowired
    private JwtAuthenticationEntryPoint unauthorizedHandler;

    @Autowired
    JwtUserDetailsService jwtUserDetailsService;

    @Bean
    public JwtAuthenticationFilter authenticationJwtTokenFilter() {

        return new JwtAuthenticationFilter();
    }

    @Bean
    public DaoAuthenticationProvider authenticationProvider() {

        DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();

        authProvider.setUserDetailsService(jwtUserDetailsService);
        authProvider.setPasswordEncoder(passwordEncoder());

        return authProvider;
    }

    @Bean
    public PasswordEncoder passwordEncoder() {

        return new BCryptPasswordEncoder();
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

        //@formatter:off
        http.csrf(csrf -> csrf.disable())
                .exceptionHandling(exception -> exception.authenticationEntryPoint(unauthorizedHandler))
                .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .authorizeHttpRequests(auth -> auth.requestMatchers("/api/auth/**").permitAll()
                                                   //.requestMatchers("/api/test/**").permitAll()
                                                   .anyRequest()
                                                   .authenticated()
                                      );
        //@formatter:on

        http.authenticationProvider(authenticationProvider());

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

        return http.build();
    }
}

JwtAuthenticationEntryPoint

@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint, Serializable {

    private static final long serialVersionUID = -7858869558953243875L;

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
            AuthenticationException authException) throws IOException {

        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
    }
}

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

英文:

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。

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

LoginController

@Slf4j
@CrossOrigin(origins = &quot;http://localhost:8080&quot;)
@RestController
@RequestMapping(&quot;/api&quot;)
public class LoginController {
@Autowired
UserRepository userRepository;
@Autowired
AuthenticationManager authenticationManager;
@PostMapping(&quot;/login&quot;)
public ResponseEntity&lt;Object&gt; login(@Validated(ValidationOrder.class) Login loginData,
BindingResult bindingResult) {
try {
Optional&lt;User&gt; user = userRepository.findByUserEmailAddress(loginData.getUserEmailAddress());
if (user.isPresent() &amp;&amp; user.get().getUserPassword().equals(loginData.getUserPassword())) {
return ResponseEntity.ok(
new RestResponse(ResponseStatus.SUCCESS.toString(), &quot;Login Success&quot;, user.get().getUserName()));
} else {
return ResponseEntity.ok(new RestResponse(ResponseStatus.ERROR.toString(),
&quot;Login Failed. Invalid username or password!!!&quot;, null));
}
} catch (Exception ex) {
log.error(null, ex);
return ResponseEntity.ok(new RestResponse(ResponseStatus.ERROR.toString(), ex.getMessage(), null));
}
}
}

ApplicationSecurity

@Configuration
@EnableMethodSecurity
public class ApplicationSecurity {//extends WebSecurityConfiguration {
@Autowired
private JwtAuthenticationEntryPoint unauthorizedHandler;
@Autowired
JwtUserDetailsService jwtUserDetailsService;
@Bean
public JwtAuthenticationFilter authenticationJwtTokenFilter() {
return new JwtAuthenticationFilter();
}
@Bean
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
authProvider.setUserDetailsService(jwtUserDetailsService);
authProvider.setPasswordEncoder(passwordEncoder());
return authProvider;
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
//@formatter:off
http.csrf(csrf -&gt; csrf.disable())
.exceptionHandling(exception -&gt; exception.authenticationEntryPoint(unauthorizedHandler))
.sessionManagement(session -&gt; session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(auth -&gt; auth.requestMatchers(&quot;/api/auth/**&quot;).permitAll()
//.requestMatchers(&quot;/api/test/**&quot;).permitAll()
.anyRequest()
.authenticated()
);
//@formatter:on
http.authenticationProvider(authenticationProvider());
http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
return http.build();
}
}

JwtAuthenticationEntryPoint

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

Any idea about this error.

答案1

得分: 1

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

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

最终它会起作用。

英文:

just add a bean in your ApplicationSecurity
what is
Global AuthenticationManager

@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:

确定