JavaMail OAuth AuthenticationFailed异常

问题描述 投票:0回答:1

我正在尝试通过javamail连接到gmail服务器并尝试通过OAuth进行身份验证。

这是执行此操作的代码。

public static void connect() {

    Properties props = System.getProperties();
    props.setProperty("mail.store.protocol", "imaps");
    props.put("mail.imaps.ssl.enable", "true"); //required for Gmail
    props.put("mail.imaps.auth.mechanisms", "XOAUTH2");

    Session session = Session.getInstance(props);
    Store store = session.getStore();
    store.connect("imap.gmail.com",  993, "[email protected]", "ya29.Glx2BW9zm7wSsr9WV66KhC4kZa7dbrOA9P6HT3EMwmiLbmkdjbHZM5oHi8VfHhxM-VNDntRxQBZ_GzMM2rMa1cAxnQ3GiNaR_M9SRfT9sCIXe0l4Rz_mNM8a40aqZw");


    Folder folder = store.getFolder("Inbox");
    IMAPFolder imapFolder = (IMAPFolder)folder;
}

但我知道,

线程“main”中的异常javax.mail.AuthenticationFailedException:[AUTHENTICATIONFAILED] com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:715)javax.mail.Service.connect上的凭据(失败)无效(服务。 Java的:366)

这里有一个相关的问题:Problems with JavaMail, GMail and OAUTH2 (not Android)

要求设定范围。但我不确定在哪里设置它。无论是在java代码还是在它之外。

你能帮帮我解决这个问题吗?

oauth-2.0 javamail google-oauth2
1个回答
0
投票

在创建访问令牌时设置范围。

这是我用来生成OAuth2令牌的shell脚本,以及说明:

#!/bin/sh

# Go to this URL in a browser:
# https://accounts.google.com/o/oauth2/auth?scope=https://mail.google.com/&redir
ect_uri=http://localhost&response_type=code&client_id=793...42.apps.googleusercontent.com
# it will display a confirmation page.  once confirmed it will redirect
# to something like this, which will fail in the browser:
# http://localhost/?code=4/0g...
# copy the code from the failed URL and use the code below

curl \
        --data-urlencode client_id=793...42
.apps.googleusercontent.com \
        --data-urlencode client_secret=<my-secret> \
        --data-urlencode 'code=4/0g...' \
        --data-urlencode redirect_uri=http://localhost \
        --data-urlencode grant_type=authorization_code \
        https://www.googleapis.com/oauth2/v3/token

显然,你需要用你的值替换client_id和secret。

© www.soinside.com 2019 - 2024. All rights reserved.