Nazar Kabylov
Nazar Kabylov

Reputation: 13

JWT Authentication Spring Boot & Swagger UI

I have a SwaggerConfig like this:

@Configuration
@EnableSwagger2
public class SwaggerConfiguration {

    public static final String AUTHORIZATION_HEADER = "Authorization";

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

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

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

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

}

When I test an API in swagger ui, it sends out the JWT fine, however it still gives an

{
  "error": "Full authentication is required to access this resource"
}

Trying out the same token in postman works fine.

Here is the swagger ui curl:

curl -X GET "http://localhost:8082/api/helloadmin" -H "accept: */*" -H "Authorization: eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJuYXoiLCJpc0FkbWluIjp0cnVlLCJleHAiOjE2MTk1MzA3MTUsImlhdCI6MTYxOTUxMjcxNX0.GvEuOYqIPuS98DqhDrtHDFhjXrtwhGjLfylEXwkPeRTGRoWxcwIAYBEawl2Bl5qoQrI2zQOjKZGDq3KEZuyALQ"

What am I doing wrong?

Upvotes: 1

Views: 2384

Answers (1)

amseager
amseager

Reputation: 6391

The correct header format is "Authorization: Bearer [token]"

Upvotes: 1

Related Questions