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


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

 

 

 

 

你可能感兴趣的:(Spring security登录新增图片验证码验证)