将鉴权方法抽取做成切面形式,通过自定义注解实现

一、背景

上游调用下游所有接口都需要在Controller层先进行鉴权再到控制层;

原来的样子:每次请求进来都需要调用一次鉴权方法

现在的样子:只需要在被上游调用的接口方法上添加@自定义注解即可

二、实现代码

首先,创建一个自定义注解

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 AuthRequired {
}

然后,创建一个类作为切面 

@Aspect
@Component
public class AuthAspect {
// com.example.AuthRequired就是你刚才创建的注解的路径和名字
@Before("@annotation(com.example.AuthRequired)")
public void beforeAuth(JoinPoint joinPoint) {
    // 获取方法参数,就是你接口的入参,请求头啊,请求体啊之类的;
    Object[] args = joinPoint.getArgs();
    // 获取自定义注解信息,MethodSignature可能会报红,导入第一个包源即可
    MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
    Method method = methodSignature.getMethod();
    AuthRequired annotation = method.getAnnotation(AuthRequired.class);
    
    // 从参数中获取 param1、param2、param3,就是你接口的入参,顺序不能改变
    String param1 = (String) args[0];
    String param2 = (String) args[1];
    String param3 = (String) args[2];
    
    // 执行自定义的鉴权逻辑,这里是你自己写的,我举个例子:鉴权成功返回的是String authResult == "200"
    String authResult = auth(param1, param2, param3);
    
    // 根据上面鉴权返回的结果,判断认证结果,这里只是举个例子给你
    if (!authResult.equals("200")) {
        // 认证失败,返回自定义的Msg
        throw new AuthException("认证失败,权限不足/账号错误/密码错误等");
    }
    
  }

}

然后就在需要鉴权的接口上使用@ AuthRequired就可以啦!

@AuthRequired
    public void someMethod(String param1, String param2, String param3, ...其他参数...) {
    // 方法内容
}

猜你喜欢

转载自blog.csdn.net/m0_73442728/article/details/133942403