• 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 参数

    1. https://accounts.google.com/o/oauth2/v2/auth?
    2. scope=https://mail.google.com/&
    3. access_type=offline&
    4. redirect_uri=http://localhost&
    5. response_type=code&
    6. 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

    1. curl \
    2. --request POST \
    3. --data "code=4/0AX4XfWhkQGEQpDSfSwE2vOUDFpoNBVYfngcBxnL0VU1PlqLXQpEQ&client_id=358916748846-epks869ps.googleusercontent.com&client_secret=GOCSPX-ItJ5x6Bou5bTj&redirect_uri=http://localhost&grant_type=authorization_code" \
    4. https://accounts.google.com/o/oauth2/token

    返回:

    1. {
    2. "access_token": "ya29.a0ARrdaM_9OV_3KTHol3hDWZnFtuxkFOCxPKBul8YZbSkjjM1L4rfx-iw35R9o4F_K27xFwwt_BJ2lzcZj5nkPyTTj-xNJ038gr9qS_z1ESQ67SJ",
    3. "expires_in": 3599,
    4. "refresh_token": "1//0efEzWtmVh6BvCgYIARAAGA4SNwF-L9IrHZNakmKqCBBpMg--p5S4d9PgG2OzQY_26P6sHYrVc",
    5. "scope": "https://mail.google.com/",
    6. "token_type": "Bearer"
    7. }

    认证参考代码1 (java)

    1. private Gmail gmailService = null;
    2. private GoogleClientSecrets clientSecrets = null;
    3. private static final String CREDENTIALS_FILE_LOCATION = "configuration/gmail/credentials.json";
    4. @PostConstruct
    5. public void init() throws IOException, GeneralSecurityException {
    6. log.info("init gmailService start ...");
    7. clientSecrets = GoogleClientSecrets.load(JsonUtils.JSON_FACTORY,
    8. new InputStreamReader(GmailUtils.class.getClassLoader().getResourceAsStream(CREDENTIALS_FILE_LOCATION)));
    9. Credential authorize = new GoogleCredential.Builder().setTransport(GoogleNetHttpTransport.newTrustedTransport())
    10. .setJsonFactory(JsonUtils.JSON_FACTORY)
    11. .setClientSecrets(clientSecrets.getDetails().getClientId(),
    12. clientSecrets.getDetails().getClientSecret())
    13. .build().setAccessToken(getAccessToken(gmailConfig.getGmailSettings().getRefreshToken(), gmailConfig.getGmailSettings().getTokenUrl()))
    14. .setRefreshToken(gmailConfig.getGmailSettings().getRefreshToken());
    15. final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
    16. gmailService = new Gmail.Builder(HTTP_TRANSPORT, JsonUtils.JSON_FACTORY, authorize)
    17. .setApplicationName(gmailConfig.getGmailSettings().getApplicationName()).build();
    18. log.info("init gmailService completed ...");
    19. }
    20. private String getAccessToken(String refreshToken, String tokenUrl) {
    21. Map params = new LinkedHashMap<>();
    22. params.put("grant_type", "refresh_token");
    23. params.put("client_id", clientSecrets.getDetails().getClientId());
    24. params.put("client_secret", clientSecrets.getDetails().getClientSecret());
    25. params.put("refresh_token", refreshToken);
    26. RequestBody authRequestBody = RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), JsonUtils.toString(params));
    27. Request request = new Request.Builder()
    28. .url(tokenUrl)
    29. .method("POST", authRequestBody)
    30. .build();
    31. String response = netUtils.executeRequest(request);
    32. JSONObject json = new JSONObject(response);
    33. return json.getString("access_token");
    34. }

     认证参考代码2 (java)

    1. public static Adsense createAdsense(AdsenseAccount account) throws IOException {
    2. HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
    3. GoogleRefreshTokenRequest request = new GoogleRefreshTokenRequest(HTTP_TRANSPORT, JsonUtils.JSON_FACTORY,
    4. account.getRefreshToken(), account.getClientId(), account.getClientSecret())
    5. .setScopes(Collections.singleton(AdsenseScopes.ADSENSE_READONLY));
    6. Credential credential = new Credential.Builder(BearerToken.authorizationHeaderAccessMethod())
    7. .setTransport(HTTP_TRANSPORT)
    8. .setJsonFactory(JsonUtils.JSON_FACTORY)
    9. .setTokenServerUrl(new GenericUrl(GoogleOAuthConstants.TOKEN_SERVER_URL))
    10. .build()
    11. .setFromTokenResponse(request.execute());
    12. return new Adsense.Builder(HTTP_TRANSPORT, JsonUtils.JSON_FACTORY, setHttpTimeout(credential)).setApplicationName("ad-data-scraper").build();
    13. }
    
                    
  • 相关阅读:
    centos 安装指定gcc版本(降级,通过yum方式)
    codeforces:B. Interesting Array【bitmask + 差分数组 + 前缀和记录是否含有1】
    Python表白代码合集:5种表白代码,找不到对象你来找我,这也太秀了叭
    【PyTorch深度学习项目实战100例】—— 基于vgg19的梵高图像风格迁移 | 第75例
    MySQL数据库管理基本操作(一)
    【打卡】牛客网:BM54 三数之和
    js基础知识整理之 —— 判断语句和三元运算符
    基于SSM的论文投稿系统
    解决TensorRT加速推理SDXL出现黑图问题
    【进阶版】机器学习之贝叶斯分类器细节回顾及原理完善(10)
  • 原文地址:https://blog.csdn.net/hantangduhey/article/details/126704183