OAuth2 / OpenID Connect configuration in Spring Boot and OpenAPI

Viewed 462

I am securing my application with OpenID Connect and Keycloak. My API documentation is OpenAPI 3 which I generate from code.

@Bean
public OpenAPI customOpenAPI() {
    OAuthFlows flows = new OAuthFlows();
    OAuthFlow flow = new OAuthFlow();
    String authUrl = authServerUrl + "/realms/" + realm + "/protocol/openid-connect/auth";
    flow.setAuthorizationUrl(authUrl);

    Scopes scopes = new Scopes();
    flow.setScopes(scopes);
    flows = flows.implicit(flow);

    return new OpenAPI()
            .components(new Components().addSecuritySchemes("keycloak",
                    new SecurityScheme().type(SecurityScheme.Type.OAUTH2).in(SecurityScheme.In.HEADER).flows(flows)))
            .info(new Info().title(appName)
                    .version(appVersion))
            .addSecurityItem(new SecurityRequirement().addList("keycloak",
                    Arrays.asList("read", "write")));
}

This works fine as I can authenticate via Keycloak's implicit flow. Now I want to secure only some endpoints and not all in my API. I tried to annotate the desired endpoint with

@SecurityRequirement(name = "keycloak")

This seems to work. When I look in the JSON api-docs of my Swagger UI HTML, I can see that this entity is added to the endpoint configuration.

The problem seems to be that it is also placed as a global statement in the docs, so it is used for every endpoint.

QUESTION:

Is there a way to define the security scheme as non-global so I can place it to specific endpoints?

I could not find much documentation on configuring OpenAPI 3 by code. I've seen a way to add it via Annotation to the main class of the object via @OpenAPIDefinition( but I could not find a documentation for it and I did not figure out how to define the openid connect specifics within this annotation.

0 Answers
Related