【问题标题】:Modifying swagger annotations at runtime在运行时修改 swagger 注释
【发布时间】:2021-07-07 15:21:38
【问题描述】:

我有一个 Swagger API 文档。我想动态隐藏的一些方法,取决于用户读取/访问 API 的权限。

由于我无法为此提供 Swagger 功能,因此我在我的服务上实现了一个 ContainerRequestFilter,它在获取 Swagger UI 的 openapi.json 文档时执行。此过滤器正在扫描所有包含 @Operation 注释的方法,并将字段 hidden 从 true 更改为 false 以供具有正确权限的用户使用。

import io.swagger.v3.oas.annotations.Operation;

@Provider
@Priority(Priorities.USER)
public class MyFilter implements ContainerRequestFilter{

    public void filter(ContainerRequestContext crc) throws IOException{

        Reflections reflections = new Reflections(new ConfigurationBuilder()
             .setUrls(ClasspathHelper.forPackage("my.package"))
             .setScanners(new MethodAnnotationsScanner()));
        
        // get all Operation methods
        Set<Method> resources = reflections.getMethodsAnnotatedWith(Operation.class);
        
        for(Method method : resources) {
            method.setAccessible(true);
    
            Operation operation = method.getAnnotation(Operation.class);
            InvocationHandler h = Proxy.getInvocationHandler(operation);
                
            Field hField = h.getClass().getDeclaredField("memberValues");
            hField.setAccessible(true);
            Map memberValues = (Map) hField.get(h);
                
            for(Object key : memberValues.keySet()) {
                System.out.println("memberValue: "+key+", "+memberValues.get(key));
            }

            memberValues.put("hidden", false);    
            System.out.println("operation is hidden?: " +operation.hidden());
        }
    }
}

代码似乎可以工作,因为隐藏字段值在此过滤器类中从 true 更改为 false。但是,从同一个服务请求返回的 openapi.json 文档并没有反映这些变化。

为什么在执行的请求中修改注解的变化不一致?

【问题讨论】:

    标签: reflection openapi jersey-2.0 swagger-2.0


    【解决方案1】:

    这种方法似乎不可行。反射会全局更改注释,因此其他请求会读取相同的更改注释,这不是我想要的。

    我最终按照here 的描述过滤了注释。

    【讨论】:

      猜你喜欢
      • 2011-03-04
      • 1970-01-01
      • 2012-12-25
      • 2020-04-04
      • 1970-01-01
      • 1970-01-01
      • 2016-12-30
      相关资源
      最近更新 更多