官方文档: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 参数
https://accounts.google.com/o/oauth2/v2/auth?scope=https://mail.google.com/&access_type=offline&redirect_uri=http://localhost&response_type=code&client_id=[your_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();}