package net.xqlee.security.interceptor;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;
@Component
public class SecurityHandlerExceptionResolver implements HandlerExceptionResolver {
private static Logger logger = LoggerFactory.getLogger(SecurityHandlerExceptionResolver.class);
private static String data = "data";
private static String code = "code";
private static String msg = "msg";
private static String date = "date";
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
Exception exception) {
// 未登陆异常捕获
// 返回错误信息
Map<String, Object> resultMap = new HashMap<>();
if (exception instanceof AuthenticationCredentialsNotFoundException) {
logger.info("User Not Login:" + request.getRequestURL());
resultMap.put(code, "00001");
resultMap.put(msg, "用户未登录");
resultMap.put(data, "");
} else if (exception instanceof AccessDeniedException) {
logger.info("Access Denied [ID:" + SecurityContextHolder.getContext().getAuthentication().getName() + "]:"
+ request.getRequestURL());
resultMap.put(code, "00001");
resultMap.put(msg, "用户权限不够");
resultMap.put(data, "");
}
//这里是核心,用jsonview方式返回
MappingJackson2JsonView jackson2JsonView = new MappingJackson2JsonView();
//设置返回的json map
jackson2JsonView.setAttributesMap(resultMap);
ModelAndView view = new ModelAndView();
view.setView(jackson2JsonView);
return view;
}
}
返回信息:
{
"msg": "用户未登录",
"data": "",
"code": "00001"
}