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

Spring Boot OAuth2授权后后续请求无Bearer Token问题

关于Spring Boot OAuth2登录后请求头是否携带Bearer Token的问题

你的配置信息

application.yml 安全配置段

security:
  oauth2:
    client:
      provider:
        auth0:
          authorization-uri: http://localhost:5556/auth0/auth
          token-uri: http://localhost:5556/auth0/token
          jwk-set-uri: http://localhost:5556/auth0/keys
      registration:
        auth0:
          client-id: sample-app
          client-secret: ZXhhbXBsZS1hcHAtc2VjcmV0
          client-name: Sample App
          scope: openid
          authorization-grant-type: authorization_code
          redirect-uri: http://localhost:8085/callback

过滤器链配置

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        
            http
                .authorizeRequests()
                .antMatchers("/callback").permitAll()
                .anyRequest().authenticated()
                .and()
                .oauth2Login();
        
    }
}

问题解答

默认情况下,通过浏览器发起的后续请求不会自动在请求头中携带Bearer Token,具体逻辑如下:

  • 你当前使用的oauth2Login()是Spring Security专门为浏览器端OAuth2授权码模式设计的登录方案。登录成功后,系统会通过Session会话维持用户身份:服务器向浏览器下发Session Cookie,后续浏览器请求会自动携带这个Cookie,Spring Security通过Cookie关联到服务器端的Session,完成身份校验,不需要在请求头中添加Bearer Token。

  • Bearer Token的典型使用场景是无Cookie的客户端(比如API测试工具、移动端应用、独立前端项目),这类场景没有Session机制,才需要每次请求手动在Authorization请求头中携带Bearer <Token>。

如果需要让前端代码调用接口时使用Bearer Token,可以按以下方式处理:

  1. 在登录成功的回调逻辑中,从OAuth2AuthenticationToken对象中提取Access Token或ID Token,将其返回给前端页面。
  2. 前端发起API请求时,手动在请求头中添加Authorization: Bearer <获取到的Token>。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 07:17:40