【发布时间】:2021-05-18 13:15:20
【问题描述】:
我需要在登录成功或失败后执行自定义操作,所以我实现了一个扩展 SimpleUrlAuthenticationFailureHandler 的类
public class CustomSimpleUrlAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
System.out.println("On authentication failure");
super.onAuthenticationFailure(request, response, exception);
}
}
还有一个扩展了 SimpleUrlAuthenticationSuccessHandler 的类
public class CustomSimpleUrlAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
System.out.println("On authentication success");
super.onAuthenticationSuccess(request, response, authentication);
}
}
然后我把它放到securityConfig中:
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(
securedEnabled = true,
jsr250Enabled = true,
prePostEnabled = true
)
@Order(SecurityProperties.IGNORED_ORDER)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private CustomUserDetailsService customUserDetailsService;
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public AuthenticationFailureHandler authenticationFailureHandler(){
return new CustomSimpleUrlAuthenticationFailureHandler();
};
@Bean
public AuthenticationSuccessHandler authenticationSuccessHandler(){
return new CustomSimpleUrlAuthenticationSuccessHandler();
};
@Override
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.httpBasic().and()
.authorizeRequests()
.antMatchers("/api/open/**").permitAll()
.anyRequest().authenticated()
.and()
.csrf()
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.ignoringAntMatchers("/api/open/**")
.and()
.formLogin()
.loginPage("/login")
.loginProcessingUrl(UrlConfigurator.API_LOGIN) // /api/login
.failureHandler(authenticationFailureHandler())
.successHandler(authenticationSuccessHandler())
.and()
.logout()
.logoutUrl("/api/logout")
.invalidateHttpSession(true)
.deleteCookies("JSESSIONID")
// .and().antMatcher("/api/service/**").csrf().disable().httpBasic()
// @formatter:on
;
}
}
但是打印命令并没有以任何方式执行... wats 错了吗?
感谢您的关注
【问题讨论】:
-
看起来您同时启用了 HTTP 基本身份验证和表单身份验证。您能否详细说明运行应用程序后所采取的步骤、您使用的 API 以及您如何进行身份验证。您能否提供您的 CustomUserDetailsService 和任何相关日志?
-
您需要身份验证过滤器并将登录 api 添加到其中,而不是您也需要覆盖尝试身份验证。
标签: spring-boot spring-security