You need to enable JavaScript to run this app. Spring应用OAuth2授权码流场景下如何提取访问令牌?
优惠活动
大模型
产品
解决方案
定价
更多

Spring应用OAuth2授权码流场景下如何提取访问令牌?

实现方案

前置准备

你已经跑通了OAuth2授权码流程,无需额外新增依赖,直接通过Spring Security提供的原生API即可提取访问令牌,下面是两种常用实现方式:


方式1:通过OAuth2AuthorizedClientService手动加载

首先在控制器中注入OAuth2AuthorizedClientService,再结合认证对象加载授权客户端即可获取令牌:

import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;

@RestController
public class OAuth2ApiController {
    // 注入Spring提供的授权客户端服务
    private final OAuth2AuthorizedClientService authorizedClientService;

    public OAuth2ApiController(OAuth2AuthorizedClientService authorizedClientService) {
        this.authorizedClientService = authorizedClientService;
    }

    // 你原本的用户信息接口
    @GetMapping("/user")
    public Map<String, Object> user(@AuthenticationPrincipal OAuth2User principal) {
        return principal.getAttributes();
    }

    // 新增的调用第三方API的接口
    @GetMapping("/call-third-api")
    public String callThirdPartyApi(OAuth2AuthenticationToken authentication) {
        // 加载当前用户的授权客户端对象
        OAuth2AuthorizedClient authorizedClient = authorizedClientService.loadAuthorizedClient(
                authentication.getAuthorizedClientRegistrationId(),
                authentication.getName()
        );
        // 提取访问令牌
        OAuth2AccessToken accessToken = authorizedClient.getAccessToken();
        String tokenValue = accessToken.getTokenValue();

        // 这里就可以用tokenValue调用服务提供商的其他API了,请求头携带Authorization: Bearer {tokenValue}即可
        return "访问令牌提取成功,前缀为:" + tokenValue.substring(0, 10);
    }
}

方式2:简化参数注入(Spring Security 5.2及以上版本支持)

无需手动注入Service,直接通过注解注入OAuth2AuthorizedClient对象,代码更简洁:

@GetMapping("/call-third-api-simple")
public String callThirdPartyApiSimple(
        @RegisteredOAuth2AuthorizedClient OAuth2AuthorizedClient authorizedClient
) {
    String tokenValue = authorizedClient.getAccessToken().getTokenValue();
    // 调用第三方API逻辑
    return "访问令牌提取成功,前缀为:" + tokenValue.substring(0, 10);
}

如果配置了多个OAuth2授权服务商,只需在注解中指定对应的客户端ID即可:
@RegisteredOAuth2AuthorizedClient("你的客户端注册ID") OAuth2AuthorizedClient authorizedClient


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 01:24:04