I have a Spring Boot 3 project and I want to show the required role/permission in the OpenApi UI for my endpoints. I have had this working before, in the past when I used Swagger instead OpenApi, however I am not sure what changes I need to make to get it to work for this.
Here is what I have:
import java.util.Optional;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Component;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.OperationBuilderPlugin;
import springfox.documentation.spi.service.contexts.OperationContext;
import springfox.documentation.spring.web.DescriptionResolver;
import springfox.documentation.swagger.common.SwaggerPluginSupport;
@Slf4j
@Component
@Order(SwaggerPluginSupport.OAS_PLUGIN_ORDER)// this used to be: SWAGGER_PLUGIN_ORDER for Swagger
@RequiredArgsConstructor
class MyOperationBuilderPlugin implements OperationBuilderPlugin {
private final DescriptionResolver descriptionResolver;
@Override
public void apply(OperationContext context) {
try {
String apiRoleAccessNoteText = "Required role: None";
Optional<PreAuthorize> preAuthorizeAnnotation = context.findAnnotation(PreAuthorize.class);
if (preAuthorizeAnnotation.isPresent()) {
apiRoleAccessNoteText =
"Required role: "
+ preAuthorizeAnnotation
.get()
.value()
.replace("hasAuthority('", "")
.replace("')", "");
}
context.operationBuilder().notes(descriptionResolver.resolve(apiRoleAccessNoteText));
} catch (Exception e) {
log.error("Error when creating swagger documentation for security roles: " + e);
}
}
@Override
public boolean supports(DocumentationType delimiter) {
return SwaggerPluginSupport.pluginDoesApply(delimiter);
}
}
The UI looks like this
However, it should show something like this (this is for a previous service using Swagger instead of OpenApi)