Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot send Authorization Bearer Token using Springfox

I'm having trouble understanding why "Authorization: Bearer __" is not being sent in my api using Springfox 2.5.0. I have the following configuration:

private ApiKey apiKey() {
        return new ApiKey(
                "Authorization", // name: My key - Authorization
                "api_key", // keyname: api_key
                "header");
    }

@Bean
    SecurityConfiguration security() {
        return new SecurityConfiguration(
                null, null, null,
                "Docserver2_fwk", // app name
                "BEARER", // api key value
                ApiKeyVehicle.HEADER, "Authorization", ",");
    }

enter image description here And the curl being sent is:

enter image description here

It seems I am unable to send "Authorization: Bearer Token" in springfox (2.5.0), is this possible?, is it a known problem?

Similar issue: https://github.com/springfox/springfox/issues/1812

PS: OpenAPI 3.0 allows the "bearer" format, example: https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#jwt-bearer-sample

Thanks.

like image 780
paulocdf Avatar asked Jan 25 '18 12:01

paulocdf


2 Answers

A simple workaround is to type Bearer than paste the token after it. You will end up with a text box that contains:

Bearer <token>

enter image description here

I wish there was a more automated way. But for now, it appears as though what goes in the text box simple get's pasted into the value section of a given header entry. I suppose the reason the prefix Bearer does not get injected automatically is because then Swagger would be quite opinionated about which sort of authentication its users used!

@Configuration
@EnableSwagger2
class SwaggerConfig {

    @Bean
    Docket api() {

        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(Predicates.not(PathSelectors.regex("/error.*")))
                .build()
                .securitySchemes(securitySchemes())
    }

    private static ArrayList<? extends SecurityScheme> securitySchemes() {

        return [new ApiKey("Bearer", "Authorization", "header")]
    }
}

The REST endpoint method:

@GetMapping("/count")
@ApiOperation(value = "Count the number of entities associated with resource name. This operation does not requires any role." , authorizations = [@Authorization(value = "Bearer")])
def count() {

    count(service)
}

The curl command before logging in:

curl -X GET "http://localhost:8080/category/count" -H "accept: */*"

Response:

{
  "timestamp": "2018-10-29T15:13:02.388+0000",
  "status": 401,
  "error": "Unauthorized",
  "message": "Unauthorized",
  "path": "/category/count"
}

The curl command after logging in:

curl -X GET "http://localhost:8080/category/count" -H "accept: */*" -H "Authorization: Bearer eyJhbGciOiJIUzUxMiJ9..."

Response:

{
  "message": "There are 0 entities",
  "count": 0
}

Note: My code is in Groovy, I am sure you can translate if you are using standard Java.

like image 165
Jabari Dash Avatar answered Oct 17 '22 03:10

Jabari Dash


I am using 2.8.0 versions and below swagger configuration works for me. I mentioned in comments, everything was working fine for me for version 2.7.0 but then I upgraded to 2.8.0 and jwt token stopped being sent in request header. I am on Spring Boot version - 1.5.2.RELEASE .

Note that I wanted an UI where JWT token could be manually entered by user is format - Bearer ... and token should go in Authorization request header. Its not automatically integrated with OAuth server.

import java.time.LocalDate;
import java.util.Arrays;
import java.util.List;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.ResponseEntity;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.AuthorizationScope;
import springfox.documentation.service.SecurityReference;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger.web.SecurityConfiguration;
import springfox.documentation.swagger.web.SecurityConfigurationBuilder;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import com.google.common.base.Predicates;
import com.google.common.collect.Lists;

@Configuration
@EnableSwagger2
public class SwaggerConfig extends WebMvcConfigurerAdapter {

    @SuppressWarnings("unchecked")
    @Bean
    public Docket swaggerPlugin() {
    return new Docket(DocumentationType.SWAGGER_2)
        .select()
        .paths(PathSelectors.any())
        .apis(Predicates.or(RequestHandlerSelectors
            .basePackage("**controller package 1**"),
            RequestHandlerSelectors
                .basePackage("**controller package 2**")))
        .build().directModelSubstitute(LocalDate.class, String.class)
        .genericModelSubstitutes(ResponseEntity.class)
        .apiInfo(apiInfo())
        .securitySchemes(Lists.newArrayList(apiKey()))
        .securityContexts(Arrays.asList(securityContext()));
    }

    private ApiInfo apiInfo() {
    return new ApiInfoBuilder().title("**Comment**")
        .description("**Comment**")
        .termsOfServiceUrl("**Comment**")
        .contact("**Comment**")
        .license("Apache License Version 2.0")
        .licenseUrl("**Comment**").version("0.0.1")
        .build();
    }

    @Bean
    public SecurityConfiguration security() {
    return SecurityConfigurationBuilder.builder().scopeSeparator(",")
        .additionalQueryStringParams(null)
        .useBasicAuthenticationWithAccessCodeGrant(false).build();
    }

    @Override
    public void addResourceHandlers(final ResourceHandlerRegistry registry) {
    registry.addResourceHandler("swagger-ui.html").addResourceLocations(
        "classpath:/META-INF/resources/");
    registry.addResourceHandler("/webjars/**").addResourceLocations(
        "classpath:/META-INF/resources/webjars/");
    }

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

    private SecurityContext securityContext() {
    return SecurityContext.builder().securityReferences(defaultAuth())
        .forPaths(PathSelectors.any()).build();
    }

    private List<SecurityReference> defaultAuth() {
    AuthorizationScope authorizationScope = new AuthorizationScope(
        "global", "accessEverything");
    AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
    authorizationScopes[0] = authorizationScope;
    return Arrays.asList(new SecurityReference("apiKey",
        authorizationScopes));
    }

}

Reference - this github issue answer by JotaroJewstar

like image 45
Sabir Khan Avatar answered Oct 17 '22 04:10

Sabir Khan