Mark
Mark

Reputation: 5612

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

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

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

Upvotes: 0

Views: 3847

Answers (2)

Mark
Mark

Reputation: 5612

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.

Upvotes: 2

ch4mp
ch4mp

Reputation: 12564

As your A service is a resource-server and you want to issue request to service B on behalf of the user who initiated the request to A, just set a Bearer Authorization header on WebClient with the original access-token string retrieved from current security context (use SecurityContextHolder static accessor or have AbstractOAuth2TokenAuthenticationToken<?> auth auto-magically injected by Spring as @Controller method parameter).

If your A service was a client, you could do as I did in the UiController of this tutorial.

Upvotes: 1

Related Questions