Search code examples
javaandroidoauth-2.0jakarta-mail

Android Javamail custom Authentication


So, I realize that SASL is not implemented in android, and that consequently the javamail oauth2 methods won't out of the box.

However, according to the google api docs for gmail imap (https://developers.google.com/google-apps/gmail/xoauth2_protocol) it would seem fairly trivial to get an auth token, encode it, and send the 'AUTHENTICATE XOAUTH2 ' to the server manually.

My problem: I want to use the javamail IMAP functions (don't want to handle IMAP protocol commands and response munging myself), but I need a way to simply insert the proper authentication command - not the traditional login username password.

Can this be done and what would be the easiest way to go about it? Could I create my own authentication method and implement this easily?

Alternatively, can I create the connection and then hand this off to an IMAPStore (doubt this would work as it creates and manages a connection pool).

---Edit---

Just to be more specific, the javax.security.sasl method is not implemented in Android which Imap.protocol.IMAPSaslAuthenticator relies on.


Solution

  • I have a working jar with sasl support for imap (for smtp you have to issue the command as you said because java mail for android doesn't have the sasl infrastructure for smtp). All I did was to add the packages javax.security.sasl and javax.security.auth.callback to the java mail for android source and repackage it. I had to put the in a different namaspace, myjavax.security.sasl etc. because otherwise android build system complains that the package contains core libraries, not sure why it doesn't complain for javax.mail which is in a core namespace anyway (javax). I also had to change some import for the new namespace in some classes, but basically are the packeges classes themselves and com.sun.mail.imap.protocol.IMAPSaslAuthenticator. With this I could successfully authenticate to gmail imap server using the oauth 2 token I got from the Android AccountManager, I didn't try anything else. For smtp, you can look at my answer here Javamail api in android using XOauth I think it's possible to make smtp work with Sasl getting the new classes from here http://kenai.com/projects/javamail/sources/mercurial/show/mail/src/main/java/com/sun/mail/smtp which have Sasl support for smtp. I think this is perfectly fine because all I do is adding some GPL classes, the one that I added are from the JDK. Hope this helps, if you need the jars or some more explanation on how to do it, just ask.