com.github.kaizen4j.shiro.advice.ShiroExceptionHandlerControllerAdvice Maven / Gradle / Ivy
package com.github.kaizen4j.shiro.advice;
import static java.net.HttpURLConnection.HTTP_NOT_FOUND;
import com.github.kaizen4j.web.entity.vo.ResponseResultVO;
import javax.servlet.http.HttpServletRequest;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
/**
* @author liuguowen
*/
@ControllerAdvice
public class ShiroExceptionHandlerControllerAdvice {
private static final Logger logger = LoggerFactory.getLogger(ShiroExceptionHandlerControllerAdvice.class);
@ExceptionHandler(value = AuthorizationException.class)
public @ResponseBody
ResponseResultVO authorizationExceptionHandler(AuthorizationException ex, HttpServletRequest request,
HandlerMethod handlerMethod) {
ResponseResultVO resultData = matchAuthorizationExceptionResponse(ex);
logger.error("授权异常:{},异常类型:{},请求方法:{},请求路径:{}", ex.getMessage(), ex.getClass(),
handlerMethod.getShortLogMessage(), request.getRequestURI());
return resultData;
}
@ExceptionHandler(value = AuthenticationException.class)
public @ResponseBody
ResponseResultVO authenticationExceptionHandler(AuthenticationException ex, HttpServletRequest request,
HandlerMethod handlerMethod) {
ResponseResultVO resultData = matchAuthenticationExceptionResponse(ex);
logger.error("认证异常:{},异常类型:{},请求方法:{},请求路径:{}", ex.getMessage(), ex.getClass(),
handlerMethod.getShortLogMessage(), request.getRequestURI());
return resultData;
}
private ResponseResultVO matchAuthorizationExceptionResponse(AuthorizationException ex) {
if (ex instanceof UnauthorizedException) {
return ResponseResultVO.unauthorized();
} else if (ex instanceof UnauthenticatedException) {
return ResponseResultVO.unauthenticated();
}
return ResponseResultVO.accessDenied();
}
private ResponseResultVO matchAuthenticationExceptionResponse(AuthenticationException ex) {
if (ex instanceof LockedAccountException) {
return ResponseResultVO.lockedUser();
} else if (ex instanceof UnknownAccountException) {
return ResponseResultVO.serverError(HTTP_NOT_FOUND, "未找到账户信息");
}
return ResponseResultVO.invalidUserPassword();
}
}