默认情况未登录和无权限都是返回403,下面我可以重写未登录和无权限的两个错误返回提示
验证为未登陆状态会进入此方法,认证错误
import com.alibaba.fastjson.JSONObject;
import com.java.core.web.vo.HttpResult;
import com.java.core.web.vo.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint, Serializable {
private static final long serialVersionUID = -8970718410437077606L;
@Override
public void commence(HttpServletRequest request,
HttpServletResponse response,
AuthenticationException authException) throws IOException {
//验证为未登陆状态会进入此方法,认证错误
response.setContentType("application/json; charset=utf-8");
HttpResult result = HttpResult.error(HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED,"登录凭证已经失效");
String json = JSONObject.toJSONString(result);
response.getWriter().print(json);
response.getWriter().flush();
response.getWriter().close();
}
}
登陆状态下,权限不足执行该方法
import com.alibaba.fastjson.JSONObject;
import com.java.core.web.vo.HttpResult;
import com.java.core.web.vo.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class AuthenticationAccessDenied implements AccessDeniedHandler {
@Override
public void handle(HttpServletRequest httpServletRequest, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {
//登陆状态下,权限不足执行该方法
response.setContentType("application/json; charset=utf-8");
HttpResult result = HttpResult.error(HttpStatus.SC_FORBIDDEN,"无访问权限");
String json = JSONObject.toJSONString(result);
response.getWriter().print(json);
response.getWriter().flush();
response.getWriter().close();
}
}
配置加上这2个
//权限自定义异常
http.exceptionHandling().accessDeniedHandler(new AuthenticationAccessDenied()).authenticationEntryPoint(new JwtAuthenticationEntryPoint());
访问的时候就能区分了
{
"code": 403,
"msg": "无访问权限"
}
{
"code": 407,
"msg": "登录凭证已经失效"
}