使用服务帐户对 gmail 进行 OAuth2 身份验证

Use service account for OAuth2 authentication to gmail

我需要在我的 gmail 应用程序中实施 OAuth2 身份验证。应用 运行 在没有 UI 的背景中。 所以我有 google 个帐户(我认为那不是 GSuite)。我按照此处的说明创建了一个服务帐户:https://www.emailarchitect.net/easendmail/sdk/html/object_oauth_service_account.htm(但没有分配产品 - 我没有为此选择。可能是因为我的帐户不是 GSuite?..)。之后我用 JSON 文件创建了一个密钥用于 JWT 身份验证。我正在使用 google-auth-library-oauth2-http 库生成 access_token 并使用它来登录 gmail 邮箱。 这是令牌生成的代码片段:

GoogleCredentials credentials = ServiceAccountCredentials.fromStream(new FileInputStream("path_to_json")
                                     .createScoped(Arrays.asList("https://mail.google.com"));
credentials.refreshIfExpired();
AccessToken accessToken = credentials.getAccessToken();

AccessToken 已成功检索,但当我尝试将其用于邮箱身份验证时,我得到 javax.mail.AuthenticationFailedException: [AUTHENTICATIONFAILED] Invalid credentials (Failure)

这里是邮箱连接的代码片段:

Properties props = new Properties();
props.put("mail.imap.ssl.enable", "true");
props.put("mail.imap.auth.mechanisms", "XOAUTH2");
Session session = Session.getInstance(props);
Store store = session.getStore("imap");
store.connect("imap.gmail.com", "my_acc@gmail.com", access_token);

问题是是否可以通过基于服务帐户数据生成的 JWT 使用访问令牌对 gmail 邮箱进行身份验证?有可能吗?

您可以在没有 G Suite 的情况下创建服务帐户,但如果您想访问用户的 Gmail 收件箱,则需要它才能使用 "Domain-wide delegation"。 正如您在 documentation:

中看到的那样

In enterprise applications you may want to programmatically access a user's data without any manual authorization on their part. In G Suite domains, the domain administrator can grant third-party applications with domain-wide access to its users' data — this is known as domain-wide delegation of authority. To delegate authority this way, domain administrators can use service accounts with OAuth 2.0.