How to add "Authorization : Bearer <token>" in header for OAuth2 implicit flows using Springdoc Open API 3 Spec

Viewed 3606

I am migrating from Springfox to Springdoc Open Api 3 and I'm trying to implement authentication flows:

Currently, I have implemented an implicit flow for authentication. Something like below :

        @Bean
        public OpenAPI customOpenAPI()
        {
            String authorizeUrl = <authorize-url>;
    
            OAuthFlow oAuthFlow = new OAuthFlow();
            oAuthFlow.authorizationUrl(authorizeUrl);
            
            return new OpenAPI()
                .components(new Components()
                        .addSecuritySchemes("OAuth", new SecurityScheme()
                                .type(Type.OAUTH2)
                                .scheme("bearer")
                                .in(In.HEADER)
                                .bearerFormat("jwt")
                                .flows(new OAuthFlows().implicit(oAuthFlow))
                                )
                        );
            
        }

Now, the problem is, I'm correctly being redirected to Keycloak server and authentication works as expected, but when I try to execute a request from Swagger UI, the Authorization:Bearer <token> is missing from the request.

I tried multiple solutions like adding security scheme requirement over the end points but it's not working. Am I missing out on something? Or my implementation flow is wrong? I need the Bearer token in each request I send out to the backend.

1 Answers

So, after trying out almost everything, following solution worked for me :

return new OpenAPI()
    .components(new Components()
        .addSecuritySchemes("OAuth", new SecurityScheme()
            .type(Type.OAUTH2)
            .scheme("bearer")
            .bearerFormat("jwt")
            .in(In.HEADER)
            .name("Authorization")
            .flows(new OAuthFlows().implicit(oAuthFlow))))
            .addSecurityItem(new SecurityRequirement().addList("OAuth"));

So, I was doing most of the configuration right, but had to add SecurityRequirement which mandates all the APIs to have the Authorization token in header.

Related