【发布时间】:2020-06-24 15:57:00
【问题描述】:
我需要在我的 gmail 应用中实现 OAuth2 身份验证。应用程序在没有 UI 的后台运行。
所以我有谷歌帐户(我认为那不是 GSuite)。我按照此处的说明创建了一个服务帐户:https://www.emailarchitect.net/easendmail/sdk/html/object_oauth_service_account.htm(但没有分配产品 - 我没有选择。可能是因为我的帐户不是 GSuite 吗?...)。之后,我使用 JSON 文件创建了一个用于 JWT 身份验证的密钥。我正在使用google-auth-library-oauth2-http 库生成access_token 并使用它登录到gmail 邮箱。
下面是生成令牌的代码 sn-p:
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)。
这里是邮箱连接的代码sn-p:
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 邮箱进行身份验证?有可能吗?
【问题讨论】:
标签: java jwt gmail jakarta-mail gmail-api