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

Spring Boot集成Swagger时出现AUTH TOKEN MISSING错误求助

问题解决:Swagger访问触发自定义认证的"AUTH TOKEN MISSING"错误

问题根源

你的自定义认证逻辑(attemptAuthentication方法)会拦截所有请求,而Swagger UI及API文档的请求未携带认证所需的Session UUID,因此触发了BadCredentialsException。

解决方案

1. 在Spring Security配置中放行Swagger相关路径

将Swagger的静态资源、API文档路径加入白名单,让这些请求跳过认证拦截。

示例配置(Spring Boot 2.7.x的SecurityFilterChain写法):

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http
        .authorizeHttpRequests(auth -> auth
            // 放行Swagger相关路径
            .antMatchers("/swagger-ui/**", "/v3/api-docs/**", "/swagger-ui-custom.html").permitAll()
            // 其他请求需要认证
            .anyRequest().authenticated()
        )
        // 挂载你的自定义认证过滤器
        .addFilterBefore(yourCustomAuthFilter(), UsernamePasswordAuthenticationFilter.class);
    return http.build();
}

2. 调整自定义认证逻辑的判断逻辑

如果不想修改Security配置,也可以在attemptAuthentication方法中先判断请求是否属于Swagger相关,若是则直接返回匿名认证对象,避免抛出异常:

@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
        throws AuthenticationException {
    // 新增:判断是否是Swagger相关请求
    String requestUri = request.getRequestURI();
    if (requestUri.contains("/swagger-ui/") || requestUri.contains("/v3/api-docs/") || requestUri.equals("/swagger-ui-custom.html")) {
        // 返回匿名认证,跳过自定义校验
        return new UsernamePasswordAuthenticationToken(null, null, Collections.emptyList());
    }

    // 原有认证逻辑
    Authentication auth = null;
    User user = null;
    Object uuid = request.getSession().getAttribute("uuid");
    if (uuid != null) {
        try {
            user = userService.findByAuthenticityToken(uuid.toString());
            user.setAuthType(AuthenticationType.valueOf(request.getSession().getAttribute("authenticationType").toString()));
            log.info("Retrieved User From Session --> " + user);
            CurrentUserContext.setCurrentUser(user);
            auth = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
        } catch (ResourceNotFoundException e) {
            log.error(e.getMessage(), e);
        }
    } else {
        log.info("No User Found with uuid");
    }

    if (isSessionRequest(request) && auth == null) {
        auth = new UsernamePasswordAuthenticationToken(null, null, null);
    }
    if (auth == null) {
        throw new BadCredentialsException("AUTH TOKEN MISSING");
    }
    return auth;
}

3. Spring 3.0迁移注意事项

  • 依赖替换:Spring 3.0需使用SpringDoc 2.x版本,替换原有依赖为:
    implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.2.0'
    
  • 配置兼容:@OpenAPIDefinition、@SecurityScheme注解在SpringDoc 2.x中依然可用,SecuritySchemeType.APIKEY用法保持不变;
  • 放行规则:Spring 3.0中Spring Security的路径匹配语法调整,antMatchers改为requestMatchers,调整后的放行规则示例:
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/swagger-ui/**", "/v3/api-docs/**", "/swagger-ui-custom.html").permitAll()
                .anyRequest().authenticated()
            )
            // 其他安全配置...
        return http.build();
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 19:42:57