OpenAPI 客户端生成器 Java - 每次调用的标头

发布于 2025-01-12 00:03:34 字数 167 浏览 0 评论 0原文

我有一个为公共和私有资源提供服务的 API。用户在调用私有资源时应传递授权标头。授权标头也可以旋转。

如何从 OpenAPI 规范文件生成的 Java 客户端指定每个出站 RPC 的 HTTP 标头?

我尝试了多个库选项,似乎都能够在客户端初始化时指定标头集。 (但不是每次调用,或者不轮换)

I have an API which serves public and private resources. User is expected to pass an authorization header while making call to private resources. Also the authorization header can rotate.

How do I specify the HTTP header per outbound RPC from generated Java client from OpenAPI specification files?

I tried multiple library options, all seem to have ability to specify set of header while initialization of the client. (but not per call, or not to rotate)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

森末i 2025-01-19 00:03:34

根据生成器,您可以使用拦截器来实现此目的,例如使用 OkHttpClient:

final okhttp3.Interceptor authTokenInterceptor = chain -> {
        Request request = chain.request();
        Request.Builder requestBuilder = request.newBuilder();
        if(request.header(AUTHORIZATION) == null) {
            // needs bearer token, only if not already present
            requestBuilder.addHeader(AUTHORIZATION,"Bearer " + tokenSuppliedByAFunction());
        }
        
        return chain.proceed(requestBuilder.build());
    };

okhttp3.OKHttpClient client = new OkHttpClient.Builder()
    .addInterceptor(authTokenInterceptor)
    .build();

虽然这是在客户端创建时提供的,但您可以编写 tokenSuppliedByAFunction() 来动态添加所需的令牌。

Depending on the generator you can use an Interceptor to achieve this, for example with OkHttpClient:

final okhttp3.Interceptor authTokenInterceptor = chain -> {
        Request request = chain.request();
        Request.Builder requestBuilder = request.newBuilder();
        if(request.header(AUTHORIZATION) == null) {
            // needs bearer token, only if not already present
            requestBuilder.addHeader(AUTHORIZATION,"Bearer " + tokenSuppliedByAFunction());
        }
        
        return chain.proceed(requestBuilder.build());
    };

okhttp3.OKHttpClient client = new OkHttpClient.Builder()
    .addInterceptor(authTokenInterceptor)
    .build();

Although this is supplied at client creation time, you can write tokenSuppliedByAFunction() to dynamically add the desired token.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文