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

如何配置Springdoc Swagger使认证头采用UTF-8编码

问题描述

项目已将编码设置为UTF-8,但通过Springdoc Swagger页面发起Basic Auth请求时,认证头仍采用ISO-8859-1编码,导致含特殊字符的密码验证失败。Postman调用同一接口可正常工作。

相关配置与代码

application.yml 配置

server:
  servlet:
    encoding:
      charset: UTF-8
      enabled: true
      force: true

端点代码

@PostMapping(value = Endpoints.USER_CHECK,
    produces = MediaType.APPLICATION_JSON_VALUE)
@Operation(
    security = @SecurityRequirement(name = AuthGroups.BASIC_AUTH))
public UserCheckResponse postUserCheck(
    @AuthenticationPrincipal UserDetails userDetails
) {
    if (userDetails == null) {
        throw new HttpClientErrorException(HttpStatus.UNAUTHORIZED,"Login failed: Credentials not set");
    }
    return portalService.postUserCheck(userDetails.getUsername(), userDetails.getPassword());
}

安全方案定义

@SecurityScheme(
    name = AuthGroups.BASIC_AUTH,
    type = SecuritySchemeType.HTTP,
    scheme = "basic"
)

测试对比

客户端输入的认证信息生成的认证头
PostmanTest:MüllAuthorization: Basic VGVzdDpNw7xsbA==
Springdoc SwaggerTest:MüllAuthorization: Basic VGVzdDpN/Gxs

更新:已确认Swagger页面的字符集为UTF-8(<html lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">),但认证头编码问题仍存在。


解决方案

问题根源在于Swagger UI默认使用ISO-8859-1编码Basic Auth凭证,而Postman采用UTF-8。需通过自定义配置强制Swagger UI使用UTF-8编码凭证。

步骤1:创建自定义配置类

添加Spring配置类,指定Swagger UI加载自定义脚本:

import org.springdoc.core.properties.SwaggerUiConfigParameters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class SwaggerUiCustomConfig {

    @Bean
    public SwaggerUiConfigParameters swaggerUiConfigParameters() {
        SwaggerUiConfigParameters config = new SwaggerUiConfigParameters();
        config.addAdditionalScript("/swagger-ui/custom-basic-auth.js");
        return config;
    }
}

步骤2:编写自定义编码脚本

在src/main/resources/static/swagger-ui/目录下创建custom-basic-auth.js文件,替换默认的Basic Auth编码逻辑:

window.onload = function() {
    const originalBasicAuth = ui.authActions.basicAuth;
    ui.authActions.basicAuth = function(username, password) {
        // 用UTF-8编码凭证,替代默认的ISO-8859-1
        const credentials = `${username}:${password}`;
        const base64Credentials = btoa(unescape(encodeURIComponent(credentials)));
        ui.preauthorizeApiKey("Basic Auth", `Basic ${base64Credentials}`);
    };
};

可选:通过配置文件指定脚本(Springdoc v1.6+)

如果使用新版本Springdoc,可直接在application.yml中添加配置,无需编写配置类:

springdoc:
  swagger-ui:
    additional-scripts:
      - /swagger-ui/custom-basic-auth.js

完成配置后重启项目,Swagger页面发起的Basic Auth请求将使用UTF-8编码凭证,特殊字符密码的验证问题即可解决。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 02:55:01