其他分享
首页 > 其他分享> > 新!Shiro自定义异常无法被捕获总是抛出AuthenticationException解决方案

新!Shiro自定义异常无法被捕获总是抛出AuthenticationException解决方案

作者:互联网

文章目录

一、出现原因

在 AuthorizingRealm doGetAuthenticationInfo 中抛出异常

案例:

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken){
        String token = (String) authenticationToken.getCredentials();

        if(true){
            throw new BusinessException("报错");
        }

结果:

{
  "timestamp": "2021-01-09T13:11:56.348+0000",
  "status": 500,
  "error": "Internal Server Error",
  "message": "Authentication failed for token submission [com.cancan.daxiangerp.utils.JWTToken@79e56cc5].  Possible unexpected error? (Typical or expected login exceptions should extend from AuthenticationException).",
  "path": "/user/dx-user/query"
}

二、当我们创建全局拦截失败

例如 @RestControllerAdvice 进行全局捕获

    /**
     * 捕捉业务相关异常
     */
    @ExceptionHandler(BusinessException.class)
    public JsonResult handle10000(BusinessException e) {
        log.error("异常{}的信息为:{}",HttpCodeEnum.BUSINESS_ERROR.getCode(),e.getMessage());
        return new JsonResult(HttpCodeEnum.BUSINESS_ERROR.getCode(), e.getMessage(), null);
    }

注意: 全局捕获失败

三、最终方案

1、返回认证失败
2、重定义响应头

        if(o == null){
            //token为null,返回错误信息,并且拒绝访问
            responseError(servletResponse, HttpCodeEnum.UNAUTHORIZED.getCode(),"token失效了!");
            return false;
        }
        JsonResult jsonResult = new JsonResult(code,errorMsg,null);
        OutputStream os = httpServletResponse.getOutputStream();
        os.write(new ObjectMapper().writeValueAsString(jsonResult).getBytes("UTF-8"));
        os.flush();
        os.close();

标签:AuthenticationException,JsonResult,自定义,异常,token,new,null,os,Shiro
来源: https://blog.csdn.net/qq_34168515/article/details/112407373