Spring AOP实现接口验签

因项目需要与外部对接,为保证接口的安全性需要使用aop进行方法的验签;
在调用方法的时候,校验外部传入的参数进行验证,
验证通过就执行被调用的方法,验证失败返回错误信息;

不是所有的方法都需要进行验签,所有使用了注解,只对注解的方法才进行验签;

创建ApiAuth注解(Annotation)

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

如果需要针对class进行验证@Target(ElementType.METHOD) 就需要改成@Target({ElementType.TYPE});

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface ApiAuthForClass {
    String id() default "";
}

创建切面类ApiAspect

@Aspect
@Component
public class ApiAspect {
}

spring aop中有这@Around @Before @After 三个注解;
@Before 是在所拦截方法执行之前执行一段逻辑。
@After 是在所拦截方法执行之后执行一段逻辑。
@Around 是可以同时在所拦截方法的前后执行一段逻辑。

我们现在使用@Around,验签通过后执行方法;

@Aspect
@Component
public class ApiAspect {

    //@Pointcut("execution(* com.example.demo..*.*(..))")
    @Pointcut("@annotation(com.example.demo.common.ApiAuth)")
    private void apiAspect() {

    }

    /**
     * @param joinPoint
     * @Around是可以同时在所拦截方法的前后执行一段逻辑
     */
    @Around("apiAspect()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        
        // 获取方法请求参数
        Object[] objs = joinPoint.getArgs();
        String[] argNames = ((MethodSignature) joinPoint.getSignature()).getParameterNames(); // 参数名
        Map<String, Object> paramMap = new HashMap<String, Object>();
        for (int i = 0; i < objs.length; i++) {
            paramMap.put(argNames[i], objs[i]);
        }

        // 获取注解的值
        ApiAuth apiAuth = ((MethodSignature) joinPoint.getSignature()).getMethod().getAnnotation(ApiAuth.class);
        String s = apiAuth.value();

        // 取得Header传递的基础数据AppKeySignedTimestamp
        // 验证是否传递了AppKey
        // 验证AppKey是否存在
        // 判定Url的时间戳调用频率是否过高
        // 验证Url的时间戳是否失
        // 验证方法是否存在
        // 验证方法是否授权操作
        // 拦截当前请求的Host地址,并对其进行匹配
        // 生成验签

        Object result = joinPoint.proceed();
        return result;

    }
}

接口使用注解

@RestController
@RequestMapping("/api/aspect")
public class ApiAspectController {

    @ApiAuth("B2887DFC-3624-4F1A-8F1D-050A4038E728")
    @RequestMapping(value = "/api")
    public void demo(String name, Integer age) {
    }
}
原文地址:https://www.cnblogs.com/amoshu/p/10401552.html