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

Swagger3中如何隐藏API级Authorization请求头(保留控制器参数)

解决Swagger UI重复显示Authorization请求头的问题

你可以通过以下两种方式隐藏API参数里的Authorization请求头,同时保留后端提取userId的逻辑:

方案一:给Authorization参数添加隐藏注解

直接在authToken参数上加上@Parameter(hidden = true)注解,Swagger就不会在UI里显示这个请求头输入框了,后端依然能正常获取到Token值。

修改后的控制器代码:

@SecurityRequirement(name = "my-notes-api")
@Operation(description = "Update the existing note", 
            summary = "Update Note", 
            tags = "Notes")
@PutMapping(path = "/update-note", 
            consumes = MediaType.APPLICATION_JSON_VALUE, 
            produces = MediaType.APPLICATION_JSON_VALUE) 
public Notes updateNote(
        @Parameter(hidden = true) // 加上这个注解隐藏Swagger中的参数显示
        @RequestHeader("Authorization") String authToken, 
        @RequestHeader("note-id") String noteId, 
        @RequestBody @Valid NotePOJO note) throws BusinessException {
                        
    return notesService.updateNote(jwtUtils.extractUserId(authToken.substring(7)), noteId, note);
    
}

方案二:全局配置自动隐藏Authorization参数

如果多个API都有这个问题,可以全局配置Swagger,自动移除所有接口中的Authorization请求头参数,避免逐个加注解:

创建一个Swagger配置类,实现OperationCustomizer接口:

import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.parameters.Parameter;
import org.springdoc.core.customizers.OperationCustomizer;
import org.springframework.stereotype.Component;

import java.util.Iterator;
import java.util.List;

@Component
public class AuthorizationHeaderHideCustomizer implements OperationCustomizer {

    @Override
    public Operation customize(Operation operation, HandlerMethod handlerMethod) {
        List<Parameter> parameters = operation.getParameters();
        if (parameters != null) {
            Iterator<Parameter> iterator = parameters.iterator();
            while (iterator.hasNext()) {
                Parameter param = iterator.next();
                // 匹配Authorization请求头,移除它
                if ("Authorization".equals(param.getName())) {
                    iterator.remove();
                }
            }
        }
        return operation;
    }
}

这样配置后,所有接口的Authorization请求头都会在Swagger UI中隐藏,后端逻辑不受影响。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 09:23:06