SpringSecurity基于表单的认证(下)

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();
}

登录认证成功,就会执行 MyAuthenticationSuccessHandleronAuthenticationSuccess 方法

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 方法

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值