spring aspect 配合自定義註解實現介面token校驗

在專案開發中,通常對所有的介面都需要做介面token校驗,為了保證程式碼簡潔,可以使用spring aspect加自定義註解方式進行token校驗,具體的實現方式如下:

一。 新增自定義註解SessionValid

@Target(ElementType。METHOD)@Retention(RetentionPolicy。RUNTIME)@Documented@Inheritedpublic @interface SessionValid {}

二。 新增aspect切面

//新增自定義註解切點 @Pointcut(“@annotation(com。zsl。web。config。SessionValid)”) public void sessionValid(){} @Autowired private UserDataConfig userDataConfig; //方法執行前進行token校驗 @Before(“sessionValid()”) public void before(JoinPoint joinPoint) throws Throwable { LOG。info(“開始進行token驗證”); Object[] args = joinPoint。getArgs(); for (Object arg:args) { if (arg == null || arg instanceof HttpServletResponse){ continue; } else if (arg instanceof HttpServletRequest) { ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder。getRequestAttributes(); HttpServletRequest request = attributes。getRequest(); String token = request。getHeader(Constants。TOKEN); LOG。info(“token>>” + token); if (StringUtils。isEmpty(token)){ throw new SessionExpireException(“未授權”); } Claims claims = userDataConfig。parseUserToken(token); if (claims。isEmpty()){ throw new SessionExpireException(“未授權”); } System。out。println(“id>>” + claims。getId()); continue; } } }

三。 在需要校驗的方法上加入註解@SessionValid

spring aspect 配合自定義註解實現介面token校驗

測試結果:

spring aspect 配合自定義註解實現介面token校驗

說明token校驗已經生效。

spring aspect 不僅可以用在驗證token,也可以用在日誌收集,介面重複請求判斷等多個應用場景。