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
相关产品推荐
相关产品推荐

