springboot:通过aop注解进行接口权限判断

本文介绍了如何使用Spring框架中的注解`@ActionRoles`实现接口级别的权限控制,包括创建注解、在接口上添加鉴权以及在`RoleAuthorizeAspect`中处理授权逻辑。
摘要由CSDN通过智能技术生成

1、创建注解

import org.springframework.core.annotation.Order;

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

/**
 * 操作权限注解
 * 可放到方法上,也可放到类上
 */
@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Order(3)
public @interface ActionRoles {
    String[] value();
}

2、在需要鉴权接口上添加直接

@PostMapping("test")
@ActionRoles(RoleType.ROLE_ADMIN)
public BiResponseDTO<String> test() {
    return BiResponseDTO.success();
}

3、创建AuthorizeAspect方法

@Slf4j
@Aspect
@Component
public class RoleAuthorizeAspect {

    @Around("@annotation(ActionRoles) || @within(ActionRoles)")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        ActionRoles annotation = point.getTarget().getClass().getAnnotation(ActionRoles.class);
        if(annotation != null){
            checkRole(annotation.value());
            return point.proceed();
        }
        //获取连接点
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        //获取方法ActionRoles注解
        annotation = method.getAnnotation(ActionRoles.class);
        if (annotation == null) {
            return point.proceed();
        }
        checkRole(annotation.value());
        return point.proceed();
    }
    
    private boolean checkRole(String[] roles) throws BaseException {
    	// 获取用户权限,与注解权限进行比较判断
        List<String> permissionList = user.getPermissionList();
        if(!ObjectUtil.isEmpty(roles) && ObjectUtil.isEmpty(permissionList)){
            log.warn("当前登录账号:{}不具备权限:{},鉴权失败");
            return false;
        }
        return true;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值