2

For work, I'm working on a Java project where we need to pass an authorization token to each request header.

In my SwaggerConfig.java file, I have the following:

@Override
public Docket createDocket() {
    return new Docket(DocumentationType.SWAGGER_2)
            .apiInfo(getApiInfo())
            ...
            .build()
            .securitySchemes(Arrays.asList(apiKey()));
}

private ApiKey apiKey() {
    return new ApiKey("Authorization", "api_key", "header");
}

This enables an Authorize button which I can click:

Swagger authorization button

And I can paste the token in here:

Swagger authorization api key dialog box

...which inserts the token into the header for each request.

However, there doesn't exist any documentation in the Swagger Docs or examples elsewhere on how I could automatically insert an auth token. The goal is to retrieve an auth token by calling an internal API (which uses active directory to authenticate) and automatically apply that token to the request headers.

I could probably extract the Swagger HTML/JS and modify the swagger-ui.html page or the JavaScript to automatically call the API and fill the dialog box with the token, but the downside with that approach is Swagger can't easily be updated if I directly modify those files.

Is there a Java way to insert a custom API key into the request headers?

homersimpson
  • 4,124
  • 4
  • 29
  • 39
  • You'll need to customize the Swagger UI web page in order to mutate "try it out" requests, [similar to this](https://stackoverflow.com/q/31057343/113116) or [this](https://stackoverflow.com/q/35267845/113116). Related: [How can I represent 'Authorization: Bearer ' in a Swagger Spec (swagger.json)](https://stackoverflow.com/q/32910065/113116). – Helen Feb 14 '18 at 19:41

1 Answers1

2

you can try this in your Configuration class

@Configuration
@EnableSwagger2
public class SwaggerConfig {                                    

    private ApiKey apiKey() {
        return new ApiKey("apiKey", "Authorization", "header");
    }

    @Bean
    public Docket api(HttpServletRequest httpReq) {
        return new Docket(DocumentationType.SWAGGER_2).select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build()
                 .securitySchemes(Arrays.asList(apiKey()));
    }
}