You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot 3中如何在OpenAPI UI展示接口所需用户角色?

Spring Boot 3 OpenAPI UI 展示接口角色/权限方案

你之前基于Springfox的Swagger插件实现,在Spring Boot3切换到OpenAPI后失效,核心原因是Springfox对Spring Boot3的支持有限,且OpenAPI规范的官方适配方案是SpringDoc OpenAPI。以下是替换后的完整实现步骤:

1. 替换依赖(Maven示例)

移除原Springfox相关依赖,添加适配Spring Boot3的SpringDoc OpenAPI依赖:

<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
    <version>2.2.0</version> <!-- 适配Spring Boot 3.x的稳定版本 -->
</dependency>

2. 实现SpringDoc自定义接口处理器

替代原Springfox的OperationBuilderPlugin,使用SpringDoc的OperationCustomizer接口解析@PreAuthorize注解,将角色信息注入到接口文档中:

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 org.springdoc.core.customizers.OperationCustomizer;
import org.springframework.web.method.HandlerMethod;
import io.swagger.v3.oas.models.Operation;

@Slf4j
@Component
@Order(1)
@RequiredArgsConstructor
public class SecurityRoleOperationCustomizer implements OperationCustomizer {

    @Override
    public Operation customize(Operation operation, HandlerMethod handlerMethod) {
        try {
            String roleInfo = "Required role: None";
            // 从接口方法上获取@PreAuthorize注解
            Optional<PreAuthorize> preAuthorizeOpt = Optional.ofNullable(
                handlerMethod.getMethodAnnotation(PreAuthorize.class)
            );

            if (preAuthorizeOpt.isPresent()) {
                String authValue = preAuthorizeOpt.get().value();
                // 解析hasAuthority/hasRole表达式,提取角色名
                String role = authValue.replace("hasAuthority('", "")
                                      .replace("')", "")
                                      .replace("hasRole('", "")
                                      .replace("ROLE_", ""); // 移除hasRole默认的ROLE_前缀,优化显示
                roleInfo = "Required role: " + role;
            }

            // 将角色信息追加到接口描述中,和原Swagger展示效果一致
            if (operation.getDescription() == null) {
                operation.setDescription(roleInfo);
            } else {
                operation.setDescription(operation.getDescription() + "<br/>" + roleInfo);
            }

        } catch (Exception e) {
            log.error("Failed to add security role info to OpenAPI docs: {}", e.getMessage(), e);
        }
        return operation;
    }
}

3. 验证效果

启动项目后访问http://localhost:8080/swagger-ui.html,每个接口的描述区域会显示对应的角色要求,和你之前使用Swagger时的展示效果完全一致。

关键说明

  • 原Springfox插件基于旧的Swagger 2规范,而Spring Boot3默认适配OpenAPI 3规范,SpringDoc是官方推荐的实现,兼容性和维护性更好。
  • 代码同时兼容hasAuthority和hasRole两种权限注解的表达式,可根据你的实际业务调整解析逻辑。

内容的提问来源于stack exchange,提问作者mr nooby noob

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 06:35:13