Spring AOP做权限控制

最近看项目代码,发现权限管理部分的代码都是直接写在controller层。

那么熟悉Spring的同学很明显发现了,这是典型的可以用切面处理的重复代码。

那么具体怎么处理呢,我先给出我的处理方式:

定义一个注解@Purview

import java.lang.annotation.*;

@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Purview {

}
这个注解中什么都不用写,就是用来做切面标记的。

然后写我们的Aspect:

import com.alibaba.fastjson.JSON;
import com.alipay.marketingservice.util.ConstantManager;
import com.alipay.opbiservice.common.Result;
import com.alipay.opbiservice.vo.UserVo;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
public class PurviewAspect {
    private static final Logger LOGGER = LoggerFactory.getLogger(LogAspect.class);

    /**
     * 捕获@Purview注解的方法,在方法执行前进行权限判断
     */
    @Before("@annotation(com.alipay.marketingservice.aspect.Purview)")
    public void doPurview(JoinPoint point) throws Throwable{
        String clazz =point.getTarget().getClass().getName();
        // 获取目标对象上正在执行的方法名
        String methodName =point.getSignature().getName();
        LOGGER.info("开始权限判断:" + clazz + "类的" + methodName + "方法");
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        Result purview = checkPurview(request);
        if (null != purview) {
            throw new Exception("权限不满足");
        }
    }
在此,对有@Purview注解的方法做一个权限判断,具体判断方法私有化出来就可以了。

当然,也可以做一些其他操作,这里就不做过多阐述了。

忙的一塌糊涂,这次就写到这里了。O(∩_∩)O~~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值