Add authorization header to Springfox

6.4k views Asked by At

I'm using spring boot with an angular 2 front end and I want to add authorization to my swagger configuration.

My current springfox setup looks like:

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket api() { 
        return new Docket(DocumentationType.SWAGGER_2)

          .select()                                  
          .apis(RequestHandlerSelectors.basePackage("mybasepackage"))
          .paths(PathSelectors.ant("/api/*"))

          .build();                                           
    }

}

My application uses a JWT filter for authorization and I want swagger to use the token as long as it's not expired in the users browser.

I saw that I could add in the HTML file like this:

function addApiKeyAuthorization() {
  var key = JSON.parse(localStorage.getItem("ls.authentication-token"));
  if (key && key.trim() != "") {
    var apiKeyAuth = new SwaggerClient.ApiKeyAuthorization("Authorization", "Bearer " + key, "header");
    window.swaggerUi.api.clientAuthorizations.add("bearer", apiKeyAuth);
    log("Set bearer token: " + key);
  }
} 

Since I'm using Springfox I don't have this option. Is there a way that I could add it via the Docket api?

2

There are 2 answers

0
Bhetzie On BEST ANSWER

I had two dependencies, springfox-swagger2 and springfox-swagger-ui. I ended up removing the springfox-swagger-ui dependency.

Jhipster used an example where they make Get calls to the packaged swagger files from springfox-swagger2. I was able to use this example with a few small changes.

I added the swagger-ui configuration to my public folder. Since I am now using the HTML file instead of generating it, I can use JavaScript to set my JWT token.

my token is not stored in JSON, so I did:

var key = localStorage.getItem("MyTokenName");

instead of

var key = JSON.parse(localStorage.getItem("MyTokenName"));
1
haihui On

In order to add your JWT token to the Authorization header, in your SwaggerConfig class, add the following bean:

@Bean
public SecurityConfiguration security() {
    return new SecurityConfiguration(null, // "client id",
            null, // "client secret",
            null, // "realm",
            null, // "app",
            "Bearer " + yourToken, ApiKeyVehicle.HEADER, "Authorization", "," /* scope separator */);
}

You can find more information here.