1. 程式人生 > >Spring AOP實現接口驗簽

Spring AOP實現接口驗簽

ron not i++ ppk 外部 strong run runtime roc

因項目需要與外部對接,為保證接口的安全性需要使用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傳遞的基礎數據AppKey\Signed\Timestamp
        // 驗證是否傳遞了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) {
    }
}

Spring AOP實現接口驗簽