SpringSecurity基于表单的认证(下)
个性化用户认证流程
1.自定义登录页面
第一步:创建自己的登录页(表单)
第二步:在配置类中配置登录页的位置,进行跳转,并且配置此url不进行身份认证,示例如下:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin()
.loginPage("/signIn.html")
.and()
.authorizeRequests()
.antMatchers("/signIn.html").permitAll()
.anyRequest()
.authenticated();
}
.antMatchers("/signIn.html").permitAll() ------- 这个是用来忽略该路径的权限认证(我们把该路径定义为表单也)
也可以将自己写好的登陆页自行配置进代码中,同样要做忽略权限判断。
2.自定义登录成功处理
需要依赖 AuthenticationSuccessHandler 类
第一步:实现自己的AuthenticationSuccessHandler
@Component("imoocAuthenticationSuccessHandler")
public class MyAuthenticationSuccessHandler extends AuthenticationSuccessHandler{
private Logger logger = LoggerFactory.getLogger(getClass());
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
logger.info("登录成功");
}
}
第二步:将此Handler配置在configure中
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin()
.loginPage("/authencation/require")
.loginProcessingUrl("/authentication/form")
.successHandler(imoocAuthenticationSuccessHandler)
.and()
.authorizeRequests()
.antMatchers("/authencation/require").permitAll()
.anyRequest()
.authenticated()
.and()
.csrf().disable();
}
登录认证成功,就会执行 MyAuthenticationSuccessHandler 中 onAuthenticationSuccess 方法
3.自定义登录失败处理
与成功处理类似,依赖 AuthenticationFailureHandler 类
第一步:实现自己的AuthenticationFailureHandler
@Component("imoocAuthenticationFailureHandler")
public class MyAuthenticationFailureHandler extends AuthenticationFailureHandler {
private Logger logger = LoggerFactory.getLogger(getClass());
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
AuthenticationException exception) throws IOException, ServletException {
logger.info("登录失败");
}
}
第二步:将此Handler配置在configure中
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin()
.loginPage("/authencation/require")
.loginProcessingUrl("/authentication/form")
.successHandler(imoocAuthenticationSuccessHandler)
.failureHandler(imoocAuthenticationFailureHandler)
.and()
.authorizeRequests()
.antMatchers("/authencation/require").permitAll()
.anyRequest()
.authenticated()
.and()
.csrf().disable();
}
登录认证失败,就会执行 **MyAuthenticationFailureHandler ** 中 onAuthenticationFailure 方法