Search code examples
oauth-2.0spring-webclientopenapi-generator

Pass Along Authorization Header in OpenAPI Generator-generated Java WebClient Code


I have a Java/Spring-based microservices architecture with two services:

  • A - has a public-facing endpoint which does some stuff and then calls the below endpoint on B. This endpoint requires an Authorization header (OAuth2) to identify the user.
  • B - has an endpoint that also requires an Authorization header (OAuth2) so that it can determine which user made the call.

I have specified B's endpoint using OpenAPI. I'm using OpenAPI Generator to generate both the client in A (Spring WebClient), and the server in B (Spring Boot).

My question is this: what do I need to do to pass the Authorization header along from A to B? I see how to set a static header, but I don't know how to pass the header based on what's received by A.

Similar to this question, but for WebClient: OpenAPI client generator Java - header per call


Solution

  • Turns out my problem was how I specified the endpoint security in my OpenAPI specification.

    I added:

    components:
      securitySchemes:
        s2s:
          type: oauth2
          flows:
            clientCredentials:
              authorizationUrl: https://example.com/oauth/authorize
              tokenUrl: https://example.com/oauth/token
              scopes:
                read: Read scope
    
    

    And made a reference to that security schema on my endpoint:

     /foo:
        get:
          ...
          security:
            - s2s:
                - read
    

    Now, when I run openapi-generate on this schema and generate it to either Spring Boot (server) or Java WebClient (client), the generated endpoint signature looks like:

        @RequestMapping(
            method = RequestMethod.GET,
            value = "/foo",
            produces = { "application/json" }
        )
        Mono<ResponseEntity<MyResponse>> foo(
            @Parameter(name = "Authorization", description = "", required = true) @RequestHeader(value = "Authorization", required = true) String authorization,
            @Parameter(hidden = true) final ServerWebExchange exchange
        );
    

    The String authorization argument to the method was not previously being generated and it's what I needed here. It allows me to pass A's header along to the call to B.

    Props to @Ch4mp for helping out here.