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

Spring Boot中Swagger 3添加Bearer Token认证失效求助

Swagger 3 配置Bearer Token认证失效的解决方案

问题描述

使用Swagger 3为API添加Bearer Token格式的Authorization认证时,通过@Parameter注解配置请求头后未生效,无法在Swagger UI中正常使用该认证调用接口。相关接口代码如下:

@Operation(
        description = "Create post, USER/ADMIN",
        responses = {
                @ApiResponse(content = @Content(schema = @Schema(implementation = PostResponseDTO.class)), responseCode = "200")})
@ApiResponses(
        value = {
                @ApiResponse(responseCode = "200", description = "200"),
                @ApiResponse(responseCode = "401", description = "401", content = @Content(schema = @Schema(implementation = ErrorDTO.class))),
                @ApiResponse(responseCode = "403", description = "403", content = @Content(schema = @Schema(implementation = ErrorDTO.class))),
                @ApiResponse(responseCode = "404", description = "404", content = @Content(schema = @Schema(implementation = ErrorDTO.class)))
        })
@PostMapping
@PreAuthorize("hasAnyRole('USER','ADMIN')")
@io.swagger.v3.oas.annotations.parameters.RequestBody(content = @Content(
        mediaType = "multipart/form-data",
        schema = @Schema(implementation = FormUpload.class)
))
@Parameter(name = "Authorization", description = "Bearer token", required = true, in = ParameterIn.HEADER)

public PostResponseDTO createPost(
        @Valid @RequestPart("post") PostRequestDTO postRequestDTO,
        @RequestPart(required = false) MultipartFile[] file) throws IOException {
   
    if (!(filesService.notEmpty(file) && filesService.isSingleFile(file) && filesService.isImageFile(file[0]) && filesService.maxSize(file[0], 5))) {
    }
    return postService.save(postRequestDTO, file);
}

Swagger UI截图:
Swagger UI截图

解决方案

方案一:全局配置(推荐)

全局配置可让所有接口统一支持Bearer Token认证,无需逐个接口添加注解:

  1. 创建Swagger配置类,定义SecurityScheme和全局SecurityRequirement:
import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import io.swagger.v3.oas.models.security.SecurityScheme;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class OpenApiConfig {

    @Bean
    public OpenAPI customOpenAPI() {
        final String securitySchemeName = "BearerAuth";
        return new OpenAPI()
                // 添加全局安全认证要求
                .addSecurityItem(new SecurityRequirement().addList(securitySchemeName))
                .components(new Components()
                        // 定义Bearer Token认证方案
                        .addSecuritySchemes(securitySchemeName,
                                new SecurityScheme()
                                        .name(securitySchemeName)
                                        .type(SecurityScheme.Type.HTTP)
                                        .scheme("bearer")
                                        .bearerFormat("JWT") // 可选,指定Token格式为JWT
                                        .in(SecurityScheme.In.HEADER)));
    }
}
  1. 配置完成后,Swagger UI顶部会出现Authorize按钮,点击后输入Bearer {你的Token}即可完成全局授权,所有接口将自动携带该认证请求头。

方案二:修复接口级配置

若仅需为单个接口配置,需修正原有@Parameter注解的使用方式,配合SecurityScheme实现:

  1. 修改接口代码,移除原@Parameter注解,在@Operation中指定安全要求:
@Operation(
        description = "Create post, USER/ADMIN",
        responses = {
                @ApiResponse(content = @Content(schema = @Schema(implementation = PostResponseDTO.class)), responseCode = "200")},
        // 指定接口使用的认证方案
        security = {@SecurityRequirement(name = "BearerAuth")}
)
@ApiResponses(
        value = {
                @ApiResponse(responseCode = "200", description = "请求成功"),
                @ApiResponse(responseCode = "401", description = "未授权", content = @Content(schema = @Schema(implementation = ErrorDTO.class))),
                @ApiResponse(responseCode = "403", description = "权限不足", content = @Content(schema = @Schema(implementation = ErrorDTO.class))),
                @ApiResponse(responseCode = "404", description = "资源不存在", content = @Content(schema = @Schema(implementation = ErrorDTO.class)))
        })
@PostMapping
@PreAuthorize("hasAnyRole('USER','ADMIN')")
@io.swagger.v3.oas.annotations.parameters.RequestBody(content = @Content(
        mediaType = "multipart/form-data",
        schema = @Schema(implementation = FormUpload.class)
))
public PostResponseDTO createPost(
        @Valid @RequestPart("post") PostRequestDTO postRequestDTO,
        @RequestPart(required = false) MultipartFile[] file) throws IOException {
   
    if (!(filesService.notEmpty(file) && filesService.isSingleFile(file) && filesService.isImageFile(file[0]) && filesService.maxSize(file[0], 5))) {
        // 补充非法文件处理逻辑
    }
    return postService.save(postRequestDTO, file);
}
  1. 需确保全局配置类中已定义名为BearerAuth的SecurityScheme(参考方案一配置),Swagger UI才能识别该认证要求。

失效原因说明

直接使用@Parameter注解添加Authorization头时,Swagger 3仅将其视为普通自定义请求头,无法识别为认证机制,因此不会提供专门的授权入口,也无法自动处理Bearer格式的Token解析。通过SecurityScheme和SecurityRequirement配置,可明确标记这是认证机制,触发Swagger UI的授权功能。

内容的提问来源于stack exchange,提问作者NqanVo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 17:55:18