springboot + aop 判断用户权限

1、pom添加aop配置

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>

2、权限注解类PrivilegeInfo

package com.test.test.web.plan.interfaces;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 权限注解
 */
@Target(ElementType.METHOD)//这个注解是应用在方法上
@Retention(RetentionPolicy.RUNTIME)
public @interface PrivilegeInfo {
    /**
     * 权限的名称
     * @return
     */
    String value() default "";
}

3、权限注解解析器

package com.test.test.web.plan.interfaces;

import java.lang.reflect.Method;
import java.util.Map;

/**
 * @auther liuy
 * @description 权限注解解析器
 * 这个解析器的主要功能,是解析目标方法上如果有PrivilegeInfo注解,那么解析出这个注解中的value值(权限的值)
 * @date 2019/5/8
 **/
public class PrivilegeAnnotationParse {
        /**
     * 解析注解
     * @param targetClass 目标类的class形式
     * @param methodName 在客户端调用哪个方法,methodName就代表哪个方法 
     * @return
     * @throws Exception
     */
    public static String parse(Class targetClass, String methodName,Class[]  clazz) throws Exception {
        String methodAccess = "";
        /*
         * 这里考虑传多个参数
         */
        Method method = targetClass.getMethod(methodName,clazz);
        //判断方法上是否有Privilege注解
        if (method.isAnnotationPresent(PrivilegeInfo.class)) {
            //得到方法上的注解
            PrivilegeInfo privilegeInfo = method.getAnnotation(PrivilegeInfo.class);
            methodAccess = privilegeInfo.value();
        }
        return methodAccess;
    }
}

4、aop配置类WebPermissionsAspect

package com.test.test.web.plan.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.longfor.gaia.gfs.core.response.BaseResponse;
import com.longfor.tender.common.entity.common.UserResources;
import com.longfor.tender.common.enums.ResponseEnum;
import com.longfor.tender.web.plan.interfaces.PrivilegeAnnotationParse;
import com.longfor.tender.web.plan.utils.SessionUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

/**
 * @auther liuy
 * @description 权限配置AOP实现类
 * @date 2019/5/8
 **/
@Aspect
@Component
@Slf4j
public class WebPermissionsAspect {

    @Pointcut("execution(public * com.longfor.tender.web.plan.controller.*.*(..))")
    public void WebPermissionsAspect(){
        log.info("开始权限验证");
    }
    @Around("WebPermissionsAspect()")
    public Object executeAround(ProceedingJoinPoint joinPoint) throws Throwable {
        // 接收到请求,记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response= attributes.getResponse();
        // 记录下请求内容
/*
        HttpServletRequest request = attributes.getRequest();
        log.info("URL : {}" , request.getRequestURL().toString());
        log.info("HTTP_METHOD : {}" , request.getMethod());
        log.info("IP : {}" + request.getRemoteAddr());
        log.info("CLASS_METHOD : {}" , joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        log.info("ARGS : {}" , Arrays.toString(joinPoint.getArgs()));*/

        boolean  bl = isHasPermission(joinPoint);
        log.info("获取权限:{}",bl);
        Object  obj =null;
        if (bl)
        {
            //用户拥有该方法权限时执行方法里面的内容
            obj =  joinPoint.proceed();
        }else{
            this.writeNoPermission(response,bl);
        }
        return obj;
    }
    /**
     * 输出没有权限的信息
     * @param response
     * @param bl
     * @throws IOException
     */
    private void writeNoPermission(HttpServletResponse response,boolean  bl) throws IOException {
        response.setHeader("Content-type","application/json; charset=UTF-8");
        OutputStream outputStream=response.getOutputStream();
        BaseResponse resultMsg = new BaseResponse(ResponseEnum.NOT_RESOURCE_PERMISSION.getRetCode(),
                ResponseEnum.NOT_RESOURCE_PERMISSION.getMessage(),bl);
        outputStream.write(new ObjectMapper().writeValueAsString(resultMsg).getBytes("UTF-8"));
    }
    /**
     * 判断用户是否拥有权限
     * @param joinPoint
     * @return
     * @throws Exception
     */
    private boolean isHasPermission(JoinPoint joinPoint) throws Exception {
        Class targetClass = joinPoint.getTarget().getClass();
        String methodName = joinPoint.getSignature().getName();
        Class[] argsClass = listArgsClass(joinPoint);
        //得到该方法的访问权限
        String methodAccess = PrivilegeAnnotationParse.parse(targetClass, methodName,argsClass);
        log.info("获取注解名:{}",methodAccess);
        if (!methodAccess.equals("")) {
            List<UserResources> userResources = SessionUtil.getSessionUserInfoBackstage().getUserResources();
            for (int i = 0; i < userResources.size(); i++) {
                UserResources userResources1 = userResources.get(i);
                if (null != userResources1.getUresourceCode() &&
                        userResources1.getUresourceCode().equals(methodAccess)
                        && userResources1.isUauthority() == true) {
                    return true;
                }

            }
            return false;
        }
        return true;
    }

    /**
     * 方法的参数数组
     * @param joinPoint
     * @return
     */
    private Class[] listArgsClass(JoinPoint joinPoint){
        Object[] declaringTypeName = joinPoint.getArgs();
        Class[] argsClass = new Class[declaringTypeName.length];
        for (int i = 0, j = declaringTypeName.length; i < j; i++) {
            argsClass[i] = declaringTypeName[i].getClass();
        }
        return argsClass;
    }
    @AfterReturning(returning = "ret", pointcut = "WebPermissionsAspect()")
    public void doAfterReturning(Object ret){
        // 处理完请求,返回内容
        log.info("RESPONSE : " + ret);
    }
}

5、接口方法

/**
     * 功能描述
     *
     * @Description: 获取删除计划的信息,判断是否要删除该计划
     * @Author: LIUY
     * @Date: 2019/1/26 11:54
     */
    @RequestMapping(value = "/checkPlanStatus")
    @PrivilegeInfo("ConstructionRegion_DataButton_Control")
    public BaseResponse checkPlanStatus(@RequestBody Map<String, String> map) {
        testPlaInfoDelEntity testPlaInfoDelEntity;
        try {
            if (null == map.get(PLAN_ID) || "".equals(PLAN_ID)) {
                return fail("参数错误");
            }
            testPlaInfoDelEntity = itdPlanInfoService.checkPlanStatus(map);
            return successToJson(testPlaInfoDelEntity);
        } catch (Exception e) {
            log.warn("获取删除信息失败", e);
            return fail("获取删除信息失败");
        }
    }

6、返回值

{
    "code": "700",
    "message": "无权访问当前页面",
    "extraCode": "",
    "extraMessage": "",
    "tracestack": null,
    "url": null,
    "data": false
}

亲测,可用!

转载于:https://my.oschina.net/maojindaoGG/blog/3047362

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值