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

Spring Boot 集成 Spring Security 使用

UnauthorizedEntryPoint.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.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import net.sf.json.JSONObject;

public class UnauthorizedEntryPoint implements AuthenticationEntryPoint {

	@Override
	public void commence(HttpServletRequest request, HttpServletResponse response,
			AuthenticationException authException) throws IOException, ServletException {
		response.setContentType("application/json;charset=utf-8");
		String requestType = request.getHeader("X-Requested-With");
		if("XMLHttpRequest".equalsIgnoreCase(requestType)) {
			JSONObject json = new JSONObject();
			if(authException instanceof InsufficientAuthenticationException) {
				try(
						PrintWriter out = response.getWriter()){
					json.element("status", "warning");
					json.element("message", "您尚未登录,请登录后再操作");
					out.write(json.toString());
					out.flush();
					out.close();
				}catch(Exception e) {}
			}
		}else {
			response.sendRedirect(request.getContextPath()+"/login?denied");
		}
		
	}

}

requestType判断是否是ajax方式登录异常。