栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java基于AspectJ的简易权限限制

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java基于AspectJ的简易权限限制

首先集成aspectJ 到项目中

集成完成后:
自定义权限注解

import java.lang.annotation.*;

@documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME) 
public @interface CheckPermission {
	String[] value();
}
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Aspect
@Component
public class ControllerAOP {
//定义切入点
    @Pointcut("execution(public * space.*.controller..*.*(..))")
    public void controllerAop() {
    }

    @Around("controllerAop()")
    public Object Around(ProceedingJoinPoint joinPoint) throws Throwable {
    //从session中获取之前存入的权限组
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        HttpSession session = requestAttributes.getRequest().getSession();
        List permissionList = (List) session.getAttribute("permissionList");
       //获取拦截的方法上使用自定义注解标注需要的权限
        CheckPermission annotation = ((MethodSignature) joinPoint.getSignature()).getMethod().getAnnotation(CheckPermission.class);
        if(annotation == null){//没加权限注解,直接放行
            return joinPoint.proceed();
        }
        //如果session中权限组含有该权限,放行
        if(permissionList.contains(annotation.value()))
            return joinPoint.proceed();
        else{
            return new ErrorResult<>("你没有权限访问~","");
        }
    }
}

测试

    @PostMapping("test")
    @CheckPermission("sys:test")//表明该方法需要sys:test权限
    public Object update(Test test){
        return testService.update(test);
    }

当访问 controller中test 方法的时候,aop会拦截请求,判断session中权限组有没有该权限。没有则拦截

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/322265.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号