Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add authorization header to Springfox

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?

like image 299
Bhetzie Avatar asked Sep 12 '26 05:09

Bhetzie


1 Answers

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.

like image 162
haihui Avatar answered Sep 14 '26 20:09

haihui