我正在编写一个带有自定义表单登录的 Spring Boot 应用程序。我尝试这样做,当我尝试登录应用程序时,我收到此错误。
org.springframework.security.authentication.ProviderNotFoundException: No AuthenticationProvider found for xxx.configuration.security.web.CustomAuthenticationToken at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:251) 我尝试了很多东西,但他们不工作。错误在哪里?我找不到它。
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
@EnableWebSecurity
@Configuration
@RequiredArgsConstructor
@Slf4j
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.addFilterBefore(authenticationFilter(), CustomAuthenticationFilter.class)
.authorizeRequests() .mvcMatchers(PublicUrls.URLS).permitAll() .anyRequest().fullyAuthenticated().and() .formLogin().loginPage("/login").defaultSuccessUrl("/").permitAll()
.and()
.cors()
.and()
.logout()
.invalidateHttpSession(true)
.clearAuthentication(true)
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/login?logout")
.permitAll();
}
public CustomAuthenticationFilter authenticationFilter() throws Exception {
CustomAuthenticationFilter filter = new CustomAuthenticationFilter();
filter.setAuthenticationManager(authenticationManagerBean());
filter.setAuthenticationFailureHandler(failureHandler());
return filter;
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authProvider());
}
public AuthenticationProvider authProvider() {
CustomAuthenticationProvider provider
= new CustomAuthenticationProvider();
return provider;
}
public SimpleUrlAuthenticationFailureHandler failureHandler() {
return new SimpleUrlAuthenticationFailureHandler("/login?error=true");
}
而 CustomAuthenticationToken 是
public class CustomAuthenticationToken extends UsernamePasswordAuthenticationToken {
@Getter
private String surname;
private String password;
private String birthDate;
public CustomAuthenticationToken(Object principal, Object credentials, String surname, String password, String birthDate) {
super(principal, credentials);
this.surname = surname;
this.password = password;
this.birthDate = birthDate;
super.setAuthenticated(false);
}
public CustomAuthenticationToken( String surname, String password, String birthDate) {
super(null, null);
this.surname = surname;
this.password = password;
this.birthDate = birthDate;
super.setAuthenticated(false);
}
public CustomAuthenticationToken(Object principal, Object credentials, String surname, String password, String birthDate,
Collection<? extends GrantedAuthority> authorities) {
super(principal, credentials, authorities);
this.surname = surname;
this.password = password;
this.birthDate = birthDate;
super.setAuthenticated(true); // must use super, as we override
}
}