Spring Boot 集成 Spring Security 使用
创建时间:2018-05-19  访问量:9044  6  2

Spring Boot 集成 Spring Security 使用

 CustomAuthenticationProcessingFilter.java

自定义认证处理过滤器,本自定义过滤器主要实现验证码过滤

package com.zxstrive.fight.sys.extend.security;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

public class CustomAuthenticationProcessingFilter extends AbstractAuthenticationProcessingFilter {
	
	public CustomAuthenticationProcessingFilter() {
		super(new AntPathRequestMatcher("/loginProcess", "POST"));
	}
	
	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
			throws IOException, ServletException {
		
		CustomAuthenticationFailureHandler customFailedHandler = (CustomAuthenticationFailureHandler)this.getFailureHandler();

		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;

		if (!requiresAuthentication(request, response)) {
			chain.doFilter(request, response);
			return;
		}
		
		String captcha = request.getParameter("captcha");
		String captchaId = (String) request.getSession().getAttribute("captcha");
		if(captcha == null || !captcha.equalsIgnoreCase(captchaId)) {
			customFailedHandler.setType("captcha");//向failureHandler报告验证码错误
			this.unsuccessfulAuthentication(request, response, new InsufficientAuthenticationException("验证码不正确"));
			return;
		}else {
			customFailedHandler.setType(null);
			chain.doFilter(request, response);
			return;
		}

	}

	@Override
	public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
			throws AuthenticationException, IOException, ServletException {
		return null;
	}
	
}

如果验证成功则执行chain.doFilter继续执行,否则告诉Spring Security认证失败,失败类型为captcha,在自定义认证失败处理器中可以区分失败原因。