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

Spring Boot 集成 Spring Security 使用

CustomAuthenticationFailureHandler.java

自定义认证失败处理器

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

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import net.sf.json.JSONObject;

public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler {
	
	/**
	 * 定义失败类型,captcha为验证码失败,否则其它失败
	 */
	private String type;

	@Override
	public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
			AuthenticationException exception) throws IOException, ServletException {
		response.setContentType("application/json;charset=utf-8");
		String requestType = request.getHeader("X-Requested-With");
		if("XMLHttpRequest".equalsIgnoreCase(requestType)) {
			try (PrintWriter out = response.getWriter()){
				JSONObject json = new JSONObject();
				json.element("status", "error");
				if("captcha".equals(type)) {
					json.element("message", "验证码不正确");
				}else {
					json.element("message", "用户名或密码不正确");
				}
				out.write(json.toString());
				out.flush();
				out.close();
			}catch(Exception e) {
				 
			}
		}else {
			if("captcha".equals(type)) {
				response.sendRedirect(request.getContextPath()+"/login?captcha");
			}else {
				response.sendRedirect(request.getContextPath()+"/login?error");
			}
		}
		
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}
	
}

认证失败处理,顺便判断一下,是验证码验证失败还是用户名密码认证失败,这是通过type来判断的,后面会介绍验证码过滤器。