我是 Spring Security 6 的新手。当我尝试配置安全性时,我收到此错误:
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 2 of constructor in com.security.Security.service.impl.AuthenticationServiceImpl required a bean of type 'org.springframework.security.authentication.AuthenticationManager' that could not be found.
Action:
Consider defining a bean of type 'org.springframework.security.authentication.AuthenticationManager' in your configuration.
Process finished with exit code 1
我在配置文件中定义了bean,以及登录、注册的方法。由于我添加了登录 api,所以出现错误。
安全配置类:
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfiguration{
@Autowired
public SecurityConfiguration(UserService userService, JWTAuthenticationFilter jwtAuthenticationFilter) {
this.userService = userService;
this.jwtAuthenticationFilter = jwtAuthenticationFilter;
}
private JWTAuthenticationFilter jwtAuthenticationFilter;
private final UserService userService;
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception{
http.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(request -> request.requestMatchers("/api/v1/auth/**")
.permitAll()
.requestMatchers("/api/v1/admin").hasAnyAuthority(Role.ADMIN.name())
.requestMatchers("/api/v1/user").hasAnyAuthority(Role.USER.name())
.anyRequest().authenticated())
.sessionManagement(manager -> manager.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authenticationProvider(authenticationProvider()).addFilterBefore(
jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class
);
return http.build();
}
@Bean
public AuthenticationProvider authenticationProvider(){
DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
authenticationProvider.setUserDetailsService(userService.userDetailsService());
authenticationProvider.setPasswordEncoder(passwordEncoder());
return authenticationProvider;
}
@Bean
protected PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception{
return config.getAuthenticationManager();
}
}
AuthenticationServiceImpl 类:
@Service
@RequiredArgsConstructor
public class AuthenticationServiceImpl implements AuthenticationService {
private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
private final AuthenticationManager authenticationManager;
private final JWTService jwtService;
public User signup(SignUpRequest signUpRequest){
User user = new User();
user.setEmail(signUpRequest.getEmail());
user.setName(signUpRequest.getName());
user.setRole(Role.USER);
user.setPassword(passwordEncoder.encode(signUpRequest.getPassword()));
return userRepository.save(user);
}
public JwtAuthenticationResponse signin(SignInRequest signInRequest){
authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(signInRequest.getEmail(),signInRequest.getPassword()));
var user = userRepository.findByEmail(signInRequest.getEmail()).orElseThrow(()-> new IllegalArgumentException("Invalid email or password"));
var jwt = jwtService.generateToken(user);
var refreshToken = jwtService.generatefreshToken(new HashMap<>(),user);
JwtAuthenticationResponse jwtAuthenticationResponse = new JwtAuthenticationResponse();
jwtAuthenticationResponse.setToken(jwt);
jwtAuthenticationResponse.setRefreshToken(refreshToken);
return jwtAuthenticationResponse;
}
}
如何正确定义 bean 以及我的代码中有什么问题?有人可以解释一下其中的参数吗?
在安全配置类中为 AuthenticationManager 添加 Bean 注解:
@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception{
return config.getAuthenticationManager();
}