0
votes

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.

1

1 Answers

1
votes

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

@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;
        };
    }
}