I need to implement OAuth2 authentication in my app for gmail. App is running in a background without UI.
So I have google account (I think that's not a GSuite). I created a Service Account following the instructions here: https://www.emailarchitect.net/easendmail/sdk/html/object_oauth_service_account.htm (but without assigning a product - I didn't have an option for that. May it be because my account is not GSuite?..). After that I created a key with JSON file for JWT authentication. I'm using google-auth-library-oauth2-http
library to generate access_token
and use it to login to gmail mailbox.
Here's the code snippet for token generation:
GoogleCredentials credentials = ServiceAccountCredentials.fromStream(new FileInputStream("path_to_json")
.createScoped(Arrays.asList("https://mail.google.com"));
credentials.refreshIfExpired();
AccessToken accessToken = credentials.getAccessToken();
AccessToken is retrieved successfully but when I'm trying to use that for mailbox authentication I'm getting javax.mail.AuthenticationFailedException: [AUTHENTICATIONFAILED] Invalid credentials (Failure)
.
Here's the code snippet for mailbox connection:
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", "[email protected]", access_token);
The question is whether it's possible to authenticate to gmail mailbox with access token via JWT generated basing on service account data? Is it even possible?
You can create a Service Account without G Suite, but you do need it to use "Domain-wide delegation" if you want to access a user's Gmail inbox. As you can read in the 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.