简体   繁体   English

实施示例代码以通过OAuth2向Gmail进行身份验证

[英]Implementing sample code for authenticating to Gmail with OAuth2

I use code from this link to access gmail imap server, because I could not find Android-friendly port of javamail with OAUTH support (javamail 1.5.2 or higher). 我使用此链接中的代码来访问gmail imap服务器,因为我找不到具有OAUTH支持(javamail 1.5.2或更高版本)的Javamail的Android友好端口。

However, the problem with this code: 但是,此代码存在以下问题:

public static IMAPStore connectToImap(String host, int port, String userEmail, String oauthToken, boolean debug) throws Exception {
    Properties props = new Properties();
    props.put("mail.imaps.sasl.enable", "true");
    props.put("mail.imaps.sasl.mechanisms", "XOAUTH2");
    props.put(OAuth2SaslClientFactory.OAUTH_TOKEN_PROP, oauthToken);
    Session session = Session.getInstance(props);
    session.setDebug(debug);

    final URLName unusedUrlName = null;
    IMAPSSLStore store = new IMAPSSLStore(session, unusedUrlName);
    final String emptyPassword = "";
    store.connect(host, port, userEmail, emptyPassword);
    return store;
}

is that a new Store object is created every time auth token is changed (expires). 是每次更改身份验证令牌(到期)都会创建一个新的Store对象。 And then I have to create a new Folder and read my messages again... 然后我必须创建一个新文件夹并再次阅读我的消息...

My question is: 我的问题是:

Is it possible to change auth token without creating a new Store object? 是否可以在不创建新Store对象的情况下更改身份验证令牌? I would like to be able to implement something like 我希望能够实现类似

store.connect("imap.gmail.com", username, oauth2_access_token) 

(example from javamail 1.5.2) to reconnect, without the need to recreate the Store object. (例如来自javamail 1.5.2的示例)重新连接,而无需重新创建Store对象。

Thank you very much! 非常感谢你!

If you need to create a new connection with the same Store you should be able to set the property to a new value and make a new connection, without creating a new Store object. 如果需要使用同一商店创建新连接,则无需创建新商店对象,就应该能够将属性设置为新值并建立新连接。 Just call props.put with the new value. 只需使用新值调用props.put。 The Session keeps a reference to the Properties object rather than making a copy of it. 会话保留对属性对象的引用,而不是对其进行复制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM