SpringBoot利用AOP进行权限拦截

1,169 阅读1分钟

一、为什么要进行权限拦截

为了保证系统安全和用户权益,对系统资源设置不同级别的权限,不同权限的对系统访问范围不同。
例如:只能登录用户才可以进行用户评价

二、利用AOP进行权限拦截

1、用户登录时,会设置Cookie值保存用户登录状态
2、定义方法verify(),使用注解@Pointcut标识该方法为切点,并指明那些类需要被拦截,那些类不需要被拦截
3、定义出拦截之前处理方法doVerify(),加上@Before注解

public class AuthorizeAspect {
    @Pointcut("execution(public * com.dongtian.testAop.controller.Comment*.*(..))" +
            "&& !execution(public * com.dongtian.testAop.controller.UserController.*(..))")
    public void verify() {}

    @Before("verify()")
    public void doVerify() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        //查询请求中有没有name为ticket的Cookie
        Cookie cookie = CookieUtil.get(request, "ticket");
        if (cookie == null) {
            log.debug("用户未登陆");
            throw new AuthorizeException();
        }
    }
}

上述代码表示了,当用户进行评论时,需要先进行登录状态校验,即判断request中是否有cookie,如果没有,将抛出自定义异常AuthorizeException

@ControllerAdvice
public class AuthorizeException extends RuntimeException {
    @ExceptionHandler(value = AuthorizeException.class)
    public ModelAndView handlerAuthorizeException(){
        return new ModelAndView("/user/login");
    }
}

@ControllerAdvice:表示全局异常统一处理的类
@ExceptionHandler(value = AuthorizeException.class):全局异常捕捉处理,当出现了 AuthorizeException异常时,该方法对其进行处理,即跳转到登录页面。