如何复用Spring Boot已有的Google登录能力调用Google API服务?
复用Spring Boot现有Google登录能力调用Google API的实现方案
核心逻辑:你当前用spring-boot-starter-oauth2-client完成的Google登录流程本身就走了标准OAuth2授权,只要提前申请对应API的访问权限,即可直接复用流程中发放的Access Token调用Google API,无需重复走独立鉴权流程。
1. 补充OAuth客户端权限范围配置
在你的应用配置(application.yml/application.properties)中,给Google客户端注册项添加你需要调用的Google API对应的scope,示例配置(以yaml为例):
spring: security: oauth2: client: registration: google: client-id: 你的Google客户端ID client-secret: 你的Google客户端密钥 # 原有登录用scope + 对应API的scope,比如调用日历API就加calendar相关scope scope: openid,profile,email,https://www.googleapis.com/auth/calendar provider: google: # 如果需要长期访问、自动刷新token,添加access_type=offline参数获取refresh token authorization-uri: https://accounts.google.com/o/oauth2/v2/auth?access_type=offline&prompt=consent
2. 获取已登录用户的有效Access Token
Spring Security已经自动存储了授权后的用户凭证,你可以通过两种方式获取:
方式1:Controller层直接注入
在需要调用API的接口方法上直接注入OAuth2AuthorizedClient对象,示例代码:
import org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient; import org.springframework.security.oauth2.client.OAuth2AuthorizedClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class GoogleApiTestController { @GetMapping("/test-calendar-api") public String testCalendarApi(@RegisteredOAuth2AuthorizedClient("google") OAuth2AuthorizedClient authorizedClient) { // 直接获取可用的Access Token,Spring会自动处理token过期刷新逻辑 String accessToken = authorizedClient.getAccessToken().getTokenValue(); // 后续用该token调用Google API即可 return "调用成功"; } }
方式2:非Controller层(Service/工具类等)获取
通过OAuth2AuthorizedClientService从安全上下文中获取凭证,示例代码:
import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.oauth2.client.OAuth2AuthorizedClient; import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class GoogleApiService { @Autowired private OAuth2AuthorizedClientService authorizedClientService; public String getValidGoogleAccessToken() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); OAuth2AuthorizedClient authorizedClient = authorizedClientService.loadAuthorizedClient( "google", authentication.getName() ); return authorizedClient.getAccessToken().getTokenValue(); } }
3. 用Access Token调用Google API
拿到token后即可直接对接Google API,如果你用Google官方提供的Java客户端库,直接将token设置到凭证对象即可,以日历API为例:
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.gson.GsonFactory; import com.google.api.services.calendar.Calendar; // 初始化Google API客户端 GoogleCredential credential = new GoogleCredential().setAccessToken(accessToken); Calendar calendarService = new Calendar.Builder( new NetHttpTransport(), new GsonFactory(), credential ).setApplicationName("你的应用名称").build(); // 正常调用API方法,比如查询当前用户的日历列表 var calendarList = calendarService.calendarList().list().execute();
注意事项
- 你添加的scope需要和你在Google Cloud控制台中开启的API权限对应,否则调用会返回权限不足错误
- 只要配置了
access_type=offline,Spring Security的OAuth2客户端会自动处理Access Token过期刷新逻辑,你不需要手动处理token刷新逻辑
内容的提问来源于stack exchange,提问作者Олег Мельник
相关产品推荐
相关产品推荐

