miller
发布于

api对外对内 注解区分

https://mp.weixin.qq.com/s/fesjDiC1il521E-8wAM66Q

根据这个特点,我们可以对所有经过网关的请求的header里添加一个字段,业务侧接口收到请求后,判断header里是否有该字段,如果有,则说明该请求来自外部,没有,则属于内部服务的调用,再根据该接口是否属于内部接口来决定是否放行该请求。

@GetMapping ( "/role/add" )
@OnlyIntranetAccess
public String onlyIntranetAccess() {
    return "该接口只允许内部服务调用";
}

@Aspect
@Component
@Slf4j
public class OnlyIntranetAccessAspect {
 @Pointcut ( "@within(org.openmmlab.platform.common.annotation.OnlyIntranetAccess)" )
 public void onlyIntranetAccessOnClass () {}
 @Pointcut ( "@annotation(org.openmmlab.platform.common.annotation.OnlyIntranetAccess)" )
 public void onlyIntranetAccessOnMethed () {
 }

 @Before ( value = "onlyIntranetAccessOnMethed() || onlyIntranetAccessOnClass()" )
 public void before () {
     HttpServletRequest hsr = (( ServletRequestAttributes ) RequestContextHolder.getRequestAttributes()) .getRequest ();
     String from = hsr.getHeader ( "from" );
     if ( !StringUtils.isEmpty( from ) && "public".equals ( from )) {
        log.error ( "This api is only allowed invoked by intranet source" );
        throw new MMException ( ReturnEnum.C_NETWORK_INTERNET_ACCESS_NOT_ALLOWED_ERROR);
            }
     }
 }

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface OnlyIntranetAccess {
}
浏览 (461)
点赞
收藏
评论