Spring security登录新增图片验证码验证

自己写一个类继承AbstractAuthenticationProcessingFilter

public class Captcha extends AbstractAuthenticationProcessingFilter{

	protected Captcha() {
		super("/login");//拦截地址
		setAuthenticationFailureHandler(new SimpleUrlAuthenticationFailureHandler("/login?error=captchaError"));//验证失败跳转地址
	}
	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;  
		HttpServletResponse res=(HttpServletResponse)response;  
//		...//验证逻辑
		//验证失败调用
		unsuccessfulAuthentication(req, res, new CaptchaException("验证码错误"));  
		
		super.doFilter(req, res, chain);
	}
	@Override
	public Authentication attemptAuthentication(HttpServletRequest request,
			HttpServletResponse response) throws AuthenticationException,
			IOException, ServletException {
		// TODO Auto-generated method stub
		return null;
	}

}


CaptchaException自定义异常,继承AuthenticationException

@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.headers().frameOptions().disable();
		//自定义登录验证码拦截器
		 http.addFilterBefore(new Captcha(),UsernamePasswordAuthenticationFilter.class);  
		 http.authorizeRequests()
		.antMatchers("/js/**").permitAll()
		.antMatchers("/images/**").permitAll()
		.antMatchers("/css/**").permitAll()
		.antMatchers("/404.html").permitAll()
		.antMatchers("/403.html").permitAll()
		.antMatchers("/verifiCode").permitAll()
		.antMatchers("/login").permitAll()
		.antMatchers("/").permitAll()
		.anyRequest().authenticated() //任何请求,登录后可以访问
		.and()
		//设置自定义拦截登录接口
		.formLogin()
		.defaultSuccessUrl("/success")
		.loginPage("/login")
		.failureUrl("/login?error=error")
		.permitAll() //登录页面用户任意访问	
		.and()
		//验证验证码
		.logout().logoutUrl("/logoutPage").logoutSuccessUrl("/login").permitAll(); //注销行为任意访问
		//其他人登录相同账号
		http.sessionManagement().maximumSessions(1).expiredUrl("/login?error=other");
		http.sessionManagement().sessionAuthenticationErrorUrl("/login?error=sessionAuthentication");
		//session过期
		//		 http.sessionManagement().invalidSessionUrl("/login?error=sessionvalidata");
		http.csrf().disable();
	}


把自己写的拦截器注入到登录验证拦截器前面验证
然后就搞定了~~~~

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值