使用AOP实现鉴权系统

使用AOP实现鉴权系统

引入依赖

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

1.注解

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

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface HasRight {
    String value() default "";
}

2.AOP


@Aspect
@Component
public class Right { //不会检验内部openfeign请求 哦
    @Before("@annotation(com.czh.right.anno.HasRight)")
    public void beforeMethod(JoinPoint joinPoint){
        System.out.println("============>AOP");
        Signature signature = joinPoint.getSignature();
        try {
            String name = signature.getName();//方法名
            String declaringTypeName = signature.getDeclaringTypeName();// 类名
            Class<?> aClass = Class.forName(declaringTypeName);//反射拿到类
            Method method = aClass.getMethod(name);
            HasRight annotation = method.getAnnotation(HasRight.class);//拿到方法上的注解信息
            HttpServletRequest request = RequestUtil.getRequest();
            System.out.println(request.getRequestURL());
            String token = request.getHeader("token");
            System.out.println(token);
            System.out.println(annotation.value());
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("进入方法前");
    }
}

3. 使用

@RestController
@RequestMapping("system")
public class TestController {

    @GetMapping("t1")
    @HasRight("all")
    public String test(){
        return "Helloworld";
    }
}

在这里插入图片描述
于是乎 你就可以在AOP切面中搞事情了。比如验证 request中携带的权限信息 对比是否符合权限 没有此权限直接返回

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值