一种简单的权限校验拦截器

首先创建一个自定义异常类

/**
*自定异常类继承了RuntimeException,使用CODE和message两个属性
*/
public class CustomException extends RuntimeException{
 private String code;
 public CustomException(String code, String message){
    super(message);
        this.code = code;
    }
  public String getCode() {
        return code;
    }
}

创建全局异常捕获类

/** @ControllerAdvice 是Controller增强器,作用是给Controller控制器添加统一的操作或处理
*搭配 @ExceptionHandler 捕获 上面定义的CustomException
一旦捕获到CustomException,通过全局异常捕获类返回错误码以及错误信息
*/

@ControllerAdvice
public class GlobalExceptionHandle {
   
    @ExceptionHandler(CustomException.class)
    @ResponseBody
    public void exceptionHandler(Exception e, HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        response.sendError(Integer.parseInt(((CustomException) e).getCode()), e.getMessage());
   }
}

使用方法

@RestController
@RequestMapping("/Common")
public class CommonController {@GetMapping("/SayHH")
    public String sayH() {
        throw new CustomException("403","鉴权失效");
    }
}

postman测试返回

{
"timestamp": "2023-02-02T08:44:14.890+0000",
"status": 403,
"error": "Forbidden",
"message": "鉴权失效",
"path": "/Common/SayHH"
}

正如上面演示,通常搭配拦截器进行鉴权校验

Token拦截器如下

public class TokenInterceptor implements HandlerInterceptor {

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String authorization = request.getHeader("TAuth");
            /**此处修改权限鉴定的具体业务*/
            if (!StringUtils.isEmpty(authorization)) {
                return true;
            } else {
                throw new CustomException("403", "鉴权失效");
            }
  }
@Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
    }
}

写完拦截器后我们需要将拦截器配置上

/**addPathPatterns增加所需拦截的路径excludePathPatterns增加例外路径*/
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
 @Override
    public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(new TokenInterceptor()).addPathPatterns("/Common/Say");
    }
}

这样一个简单的权限拦截器就完成了

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值