I’m working on a Java application that connects to Gmail using XOAUTH authentication, but I keep running into authentication problems. Every time I try to connect, I get an “Invalid credentials” error message. I’ve been searching for solutions but haven’t found anything that works.
Here’s my implementation:
public class GmailAuth {
private static final String API_SCOPE = "https://mail.google.com/";
private static final String CLIENT_ID = "your_client_id";
private static final String CLIENT_SECRET = "your_client_secret";
private static final String EMAIL_ADDRESS = "[email protected]";
public static void main(String[] args) throws Exception {
GoogleOAuthParameters authParams = new GoogleOAuthParameters();
authParams.setOAuthConsumerKey(CLIENT_ID);
authParams.setOAuthConsumerSecret(CLIENT_SECRET);
OAuthSigner signature = new OAuthHmacSha1Signer();
GoogleOAuthHelper authHelper = new GoogleOAuthHelper(signature);
authParams.setScope(API_SCOPE);
authHelper.getUnauthorizedRequestToken(authParams);
String authUrl = authHelper.createUserAuthorizationUrl(authParams);
System.out.println(authUrl);
System.out.println("Visit this URL to authorize the token, then press enter...");
System.in.read();
String accessToken = authHelper.getAccessToken(authParams);
System.out.println("Access Token: " + accessToken);
// Connect to IMAP
XoauthAuthenticator.initialize();
IMAPSSLStore store = XoauthAuthenticator.connectToImap(
"imap.gmail.com",
993,
EMAIL_ADDRESS,
authParams.getOAuthToken(),
authParams.getOAuthTokenSecret(),
new OAuthConsumer(null, CLIENT_ID, CLIENT_SECRET, null),
true
);
System.out.println("IMAP connection successful");
}
}
The error I’m getting is:
A1 NO [ALERT] Invalid credentials (Failure)
javax.mail.AuthenticationFailedException: [ALERT] Invalid credentials (Failure)
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:660)
at javax.mail.Service.connect(Service.java:295)
I’ve tried using real consumer credentials but still get the same error. My goal is to authenticate users and access their Gmail messages for processing. Has anyone solved this authentication issue before?