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

Spring Boot 集成 Spring Security 使用

CustomAccessDeniedHandler.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.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import net.sf.json.JSONObject;

public class CustomAccessDeniedHandler implements AccessDeniedHandler {

	@Override
	public void handle(HttpServletRequest request, HttpServletResponse response,
			AccessDeniedException accessDeniedException) 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");
				json.element("message", "您无权访问");
				out.write(json.toString());
				out.flush();
				out.close();
			}catch(Exception e) {}
		}else {
			response.sendRedirect(request.getContextPath()+"/login?denied");
		}

	}

}

通过requestType判断是否是异常请求,如果是异步请求,就返回json数据,否则返回到登录页面,并提示“无权访问”。