英文:
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.
***************************
APPLICATION FAILED TO START
***************************
Description:
Field authenticationManager in com.myapp.controller.LoginController required a bean of type 'org.springframework.security.authentication.AuthenticationManager' 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 'org.springframework.security.authentication.AuthenticationManager' in your configuration.
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 {//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 -> 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");
}
}
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论