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

Spring Boot+Next.js添加Bearer Token仍提示“需完整认证”问题排查

认证失败排查:Spring Boot + Next.js/Refine 前端请求受保护端点返回"Full Authentication is required"

问题描述

API在Postman和Swagger中(包括受认证保护的端点)运行完全正常,但在Next.js结合Refine框架的前端应用中,仅/login和/register端点可用,访问其他端点会收到错误:

Full Authentication is required to access this resource

已尝试的操作

  1. 添加Bearer Token到请求头
    在前端请求中尝试携带认证Token,代码如下:

    getList: async ({ resource, pagination, sorters, filters, meta }) => {
        const auth = Cookies.get("auth");
        const token = auth ? JSON.parse(auth)?.accessToken.toString() : null;
        const { current, pageSize } = pagination ?? {};
    
        try {
          const response = await fetch(`${API_URL}/${resource}`, {
            method: "GET",
            headers: {
              "Content-Type": "application/json",
              Authorization: token ? `Bearer ${token}` : "",
            },
          }).then((res) => {
            if (res.ok) {
              return res.json();
            } else {
              throw new Error("Network response was not ok");
            }
          });
    
          const data = await response.json();
          const total = data?.length;
    
          return {
            data,
            total,
          };
        } catch (error) {
          console.error("Fetch error:", error);
          throw error; // Re-throw the error after logging it
        }
    },
    
  2. Spring Security 配置
    后端将/login和/register设为公开,其他端点需认证,代码如下:

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.csrf(csrf -> csrf.disable())
            .exceptionHandling(exception -> exception.authenticationEntryPoint(unauthorizedHandler))
            .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            .authorizeHttpRequests(auth -> auth.antMatchers("/api/users/**").permitAll()
                .antMatchers("/actuator/**").permitAll()
                .antMatchers("/").permitAll() // allow swagger
                .antMatchers("/swagger-ui/**").permitAll() // allow swagger
                .antMatchers("/v3/api-docs/**").permitAll() // internal swagger urls
                .anyRequest().authenticated());
    
        http.authenticationProvider(authenticationProvider());
    
        http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
    
        return http.build();
    }
    
  3. CORS配置
    配置CORS允许前端跨域请求,代码如下:

    @Configuration
    @EnableWebMvc
    public class CorsConfiguration implements WebMvcConfigurer {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**").allowedMethods("GET", "POST", "PUT", "DELETE", "OPTION").allowedOrigins("*");
        }
    
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            //enabling swagger-ui part for visual documentation
            registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
            registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
        }
    
        @Override
        public void addViewControllers(ViewControllerRegistry registry) {
            registry.addRedirectViewController("/","swagger-ui.html" );
        }
    }
    

可能的原因及解决方案

1. 前端Token传递逻辑错误

  • 重复解析JSON:代码中fetch已通过.then(res => res.json())解析响应,后续调用response.json()会抛出异常,中断请求逻辑。应直接使用const data = response;
  • 空Token处理不当:当token为空时,Authorization头被设为空字符串,易导致后端解析异常。改为仅在token存在时添加该头:
    headers: {
      "Content-Type": "application/json",
      ...(token && { Authorization: `Bearer ${token}` })
    }
    
  • Token有效性验证:在前端打印token值,确认是否正确从Cookie获取、格式是否符合JWT规范、是否已过期。

2. Spring Security JWT过滤器问题

  • 过滤器实现缺陷:检查authenticationJwtTokenFilter()是否正确从请求头提取Bearer Token,是否正确验证签名、过期时间、issuer等信息。可在过滤器中添加日志,打印收到的Authorization头内容,确认后端是否接收到正确的token。
  • 过滤器顺序错误:确保addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class)顺序正确,保证JWT认证在用户名密码认证之前执行。
  • 认证Provider配置:确认authenticationProvider()是否正确配置,能否处理JWT认证后的用户信息。

3. CORS配置冲突或遗漏

  • 允许OPTIONS请求:Spring Security默认拦截OPTIONS预检请求,需在配置中明确放行:
    .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
    
  • 替换CORS配置方式:@EnableWebMvc可能与Spring Boot自动配置冲突,改用CorsFilter Bean方式配置CORS,避免冲突:
    @Configuration
    public class CorsConfig {
        @Bean
        public CorsFilter corsFilter() {
            UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
            CorsConfiguration config = new CorsConfiguration();
            config.setAllowCredentials(true);
            config.addAllowedOriginPattern("*");
            config.addAllowedHeader("*");
            config.addAllowedMethod("*");
            source.registerCorsConfiguration("/**", config);
            return new CorsFilter(source);
        }
    }
    

4. 请求路径匹配问题

  • 路径前缀不一致:检查前端API_URL是否包含后端要求的/api前缀,确保拼接后的请求路径(如${API_URL}/${resource})与后端接口路径完全匹配。
  • Spring Security路径匹配规则:确认antMatchers中的路径是否正确覆盖所有公开和受保护端点,避免因路径书写错误(如斜杠、大小写)导致认证规则不生效。

快速排查步骤

  1. 打开浏览器开发者工具,查看Network面板,确认Authorization头是否正确携带Bearer {token}。
  2. 在后端JWT过滤器中添加日志,打印收到的Authorization头,确认后端是否接收到正确的token。
  3. 复制前端请求的完整头信息到Postman,测试能否正常访问受保护端点,排除token本身的问题。
  4. 检查JWT Token的有效期,确认请求时token未过期。

内容的提问来源于stack exchange,提问作者Yunus Emre Alpu

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 00:39:53