Google Gmail Oauth Client ID 认证指南
官方文檔:https://developers.google.com/workspace/guides/configure-oauth-consent
https://developers.google.com/workspace/guides/create-credentials
參考視頻:https://www.youtube.com/watch?v=tGDn3V-mIOM
https://www.youtube.com/watch?v=IZ1ZEjuJF8U
OAuth2 client ID and client secret
新建 project
project 控制臺:https://console.cloud.google.com/cloud-resource-manager
?
?
Enable Gmail Api
?
?
?
點擊 Gmail Api 并 Enable
?
新建 app
控制臺:https://console.cloud.google.com/apis/credentials/consent
打開控制臺,選擇 project:
?
?
點擊菜單 OAuth consent screen,新建 app
?
?
注:User type 只能選擇 External,Internal 是給 Google Worksapce 用戶使用的,是個收費的產品
step1:
?
?
?
step2:Scopes
這一步暫時不選擇,直接 ’保存并繼續‘
step3: add test users
?
?
step4:創建完成
?
?
step5: 發布 app,使 app 狀態處于 In production 狀態,防止 refresh token 失效
?
?
?
?
新建 OAuth 2.0 Client
控制臺地址:https://console.developers.google.com/apis/credentials
點擊 Credentials 菜單
?
?
?
保存并下載 .json 文件,可以命名為 credentials.json
?
獲取 scope 對應的 code
瀏覽器中請求如下 url
-
scope 是需要的權限 https://developers.google.com/gmail/api/auth/scopes
-
[your_client_id] 是上一步 credentials.json 中的 client_id 參數
請求之后,瀏覽器地址欄會出現如下鏈接
http://localhost/?code=4/0AX4XfWhkQGEQpDSfSwE2vOUDFpoNBLha_KBVYfngcBxnL0qLXQpEQ&scope=https://mail.google.com/code 參數即我們需要的值
獲取 access_token 和 refresh_token
Wsl 執行如下 url,code 來自上一步獲取的 code,client_id,client_secret 均來自 credentials.json
curl \ --request POST \ --data "code=4/0AX4XfWhkQGEQpDSfSwE2vOUDFpoNBVYfngcBxnL0VU1PlqLXQpEQ&client_id=358916748846-epks869ps.googleusercontent.com&client_secret=GOCSPX-ItJ5x6Bou5bTj&redirect_uri=http://localhost&grant_type=authorization_code" \ https://accounts.google.com/o/oauth2/token返回:
{"access_token": "ya29.a0ARrdaM_9OV_3KTHol3hDWZnFtuxkFOCxPKBul8YZbSkjjM1L4rfx-iw35R9o4F_K27xFwwt_BJ2lzcZj5nkPyTTj-xNJ038gr9qS_z1ESQ67SJ","expires_in": 3599,"refresh_token": "1//0efEzWtmVh6BvCgYIARAAGA4SNwF-L9IrHZNakmKqCBBpMg--p5S4d9PgG2OzQY_26P6sHYrVc","scope": "https://mail.google.com/","token_type": "Bearer" }認證參考代碼1 (java)
private Gmail gmailService = null; private GoogleClientSecrets clientSecrets = null; private static final String CREDENTIALS_FILE_LOCATION = "configuration/gmail/credentials.json";@PostConstruct public void init() throws IOException, GeneralSecurityException {log.info("init gmailService start ...");clientSecrets = GoogleClientSecrets.load(JsonUtils.JSON_FACTORY,new InputStreamReader(GmailUtils.class.getClassLoader().getResourceAsStream(CREDENTIALS_FILE_LOCATION)));Credential authorize = new GoogleCredential.Builder().setTransport(GoogleNetHttpTransport.newTrustedTransport()).setJsonFactory(JsonUtils.JSON_FACTORY).setClientSecrets(clientSecrets.getDetails().getClientId(),clientSecrets.getDetails().getClientSecret()).build().setAccessToken(getAccessToken(gmailConfig.getGmailSettings().getRefreshToken(), gmailConfig.getGmailSettings().getTokenUrl())).setRefreshToken(gmailConfig.getGmailSettings().getRefreshToken());final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();gmailService = new Gmail.Builder(HTTP_TRANSPORT, JsonUtils.JSON_FACTORY, authorize).setApplicationName(gmailConfig.getGmailSettings().getApplicationName()).build();log.info("init gmailService completed ..."); }private String getAccessToken(String refreshToken, String tokenUrl) {Map<String, Object> params = new LinkedHashMap<>();params.put("grant_type", "refresh_token");params.put("client_id", clientSecrets.getDetails().getClientId());params.put("client_secret", clientSecrets.getDetails().getClientSecret());params.put("refresh_token", refreshToken);RequestBody authRequestBody = RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), JsonUtils.toString(params));Request request = new Request.Builder().url(tokenUrl).method("POST", authRequestBody).build();String response = netUtils.executeRequest(request);JSONObject json = new JSONObject(response);return json.getString("access_token"); }?認證參考代碼2 (java)
public static Adsense createAdsense(AdsenseAccount account) throws IOException {HttpTransport HTTP_TRANSPORT = new NetHttpTransport();GoogleRefreshTokenRequest request = new GoogleRefreshTokenRequest(HTTP_TRANSPORT, JsonUtils.JSON_FACTORY,account.getRefreshToken(), account.getClientId(), account.getClientSecret()).setScopes(Collections.singleton(AdsenseScopes.ADSENSE_READONLY));Credential credential = new Credential.Builder(BearerToken.authorizationHeaderAccessMethod()).setTransport(HTTP_TRANSPORT).setJsonFactory(JsonUtils.JSON_FACTORY).setTokenServerUrl(new GenericUrl(GoogleOAuthConstants.TOKEN_SERVER_URL)).build().setFromTokenResponse(request.execute());return new Adsense.Builder(HTTP_TRANSPORT, JsonUtils.JSON_FACTORY, setHttpTimeout(credential)).setApplicationName("ad-data-scraper").build();}總結
以上是生活随笔為你收集整理的Google Gmail Oauth Client ID 认证指南的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何在Linux上创建手册页
- 下一篇: springboot切面不生效踩坑纪录