认证成功处理器

实际上在UsernamePasswordAuthenticationFilter进行登录认证的时候,如果登录成功了是会调用
AuthenticationSuccessHandler的方法进行认证成功后的处理的。AuthenticationSuccessHandler就是登录成功处理器。

我们也可以自己去自定义成功处理器进行成功后的相应处理。

@Component
public class SuccessHandler implements AuthenticationSuccessHandler {
	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
		System.out.println("认证成功了");
	}
}

认证失败处理器

实际上在UsernamePasswordAuthenticationFilter进行登录认证的时候,如果认证失败了是会调用
AuthenticationFailureHandler的方法进行认证失败后的处理的。AuthenticationFailureHandler就是
登录失败处理器。

我们也可以自己去自定义失败处理器进行失败后的相应处理。

@Component
public class FailureHandler implements AuthenticationFailureHandler {
	@Override
	public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
		System.out.println("认证失败了");
	}
}

登出成功处理器

默认是post请求,默认访问路径是/logout。

@Component
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler {
	@Override
	public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
		//在这里清除redis缓存中的登录数据
	}
}

加载这些处理器到SecurityConfig中

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
	@Autowired
	private AuthenticationSuccessHandler successHandler;
	@Autowired
	private AuthenticationFailureHandler failureHandler;
	@Autowired
	private LogoutSuccessHandler logoutSuccessHandler;
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.formLogin()
			// 配置认证成功处理器
			.successHandler(successHandler)
			// 配置认证失败处理器
			.failureHandler(failureHandler);
			
		http.logout()
			//配置注销成功处理器
			.logoutSuccessHandler(logoutSuccessHandler);
			
		http.authorizeRequests().anyRequest().authenticated();
	}
}
Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐