Y. Sobelman
Y. Sobelman

Reputation: 396

Automatic Swagger annotation-based description generation in Springdoc

Basically my question is the same as this one but for Springdoc (and not Springfox).

In short, I have a Spring-boot app and I am using spring-security @PreAuthorize annotation to secure some of my apis, currently based on hasAuthority only.

Is there a way I can automatically modify the specific resource swagger description based on the annotation? I guess it has something to do with overriding one of Springdoc's default class behaviors (maybe OpenAPICustomiser?) but I'm not sure how to do it.

Upvotes: 5

Views: 2261

Answers (1)

Y. Sobelman
Y. Sobelman

Reputation: 396

OK, I've figured it out with something like this-

import org.springdoc.core.customizers.OperationCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.prepost.PreAuthorize;
import java.util.Optional;

@Configuration
public class SpringdocPreAuthorize {
    @Bean
    public OperationCustomizer operationCustomizer() {
        return (operation, handlerMethod) -> {
            Optional<PreAuthorize> preAuthorizeAnnotation = Optional.ofNullable(handlerMethod.getMethodAnnotation(PreAuthorize.class));
            StringBuilder sb = new StringBuilder();
            if (preAuthorizeAnnotation.isPresent()) {
                sb.append("This api requires **")
                        .append((preAuthorizeAnnotation.get()).value().replaceAll("hasAuthority|\\(|\\)|\\'", ""))
                        .append("** permission.");
            } else {
                sb.append("This api is **public**");
            }
            sb.append("<br /><br />");
            sb.append(operation.getDescription());
            operation.setDescription(sb.toString());
            return operation;
        };
    }
}

Upvotes: 9

Related Questions