Tools and sample code for authenticating to Gmail with OAuth2.
The specification is available here.
Instructions for using the sample code and libraries is available on the wiki.
The discussion forum is [email protected].
Tools and sample code for authenticating to Gmail with OAuth2
License: Apache License 2.0
Tools and sample code for authenticating to Gmail with OAuth2.
The specification is available here.
Instructions for using the sample code and libraries is available on the wiki.
The discussion forum is [email protected].
Hi,
After an upgrade on my system today (Archlinux), I could not make offlineimap sync with gmail. I've tried to generate a new token and got a similar error :
λ python2 python/oauth2.py --generate_oauth2_token --client_id=XX=--client_secret=YY
To authorize token, visit this url and follow the directions:
https://accounts.google.com/o/oauth2/ZZZZ
Enter verification code: WWWWW
Traceback (most recent call last):
File "python/oauth2.py", line 347, in <module>
main(sys.argv)
File "python/oauth2.py", line 326, in main
authorization_code)
File "python/oauth2.py", line 214, in AuthorizeTokens
response = urllib.urlopen(request_url, urllib.urlencode(params)).read()
File "/usr/lib/python2.7/socket.py", line 355, in read
data = self._sock.recv(rbufsize)
File "/usr/lib/python2.7/ssl.py", line 754, in recv
return self.read(buflen)
File "/usr/lib/python2.7/ssl.py", line 641, in read
v = self._sslobj.read(len)
ssl.SSLError: [SSL: KRB5_S_TKT_NYV] unexpected eof while reading (_ssl.c:1946)
Any advice ? Thanks
I'm trying to set up offlineimap to sync my mail from gmail. As the guide in .offlineimaprc.full
mentions this repo I've cloned it and trying to run:
# ./oauth2.py --generate_oauth2_token --client_id=$my_client_id --client_secret=$my_secret
To authorize token, visit this url and follow the directions:
https://accounts.google.com/o/oauth2/auth?client_id=$my_client_id&redirect_uri=$my_url&response_type=code&scope=https%3A%2F%2Fmail.google.com%2F
Enter verification code: $my_auth_code
but I've got a KeyError on 'refresh_token':
Traceback (most recent call last):
File "./oauth2.py", line 347, in <module>
main(sys.argv)
File "./oauth2.py", line 327, in main
print 'Refresh Token: %s' % response['refresh_token']
KeyError: 'refresh_token'
So I've added some prints to see the response:
{
u'access_token': u'$my_access_token',
u'scope': u'https://mail.google.com/',
u'expires_in': 3585,
u'token_type': u'Bearer'
}
Access_token is fine, auth works but for a single hour only. But I want a permanent solution mentioned in this wiki page. Am I doing something wrong? Problem seems to be on API side, maybe something is changed and not shown in the docs yet?
I've been using oauth2.py
script for the last couple of months but this week it started tripping over. I have been able to debug it a little, but it seems the problem is with the server connection.
~/bin/oauth2.py \
[email protected] \
--client_id=*** \
--client_secret=*** \
--refresh_token=***
When I print respone
variable I get:
{u'error_description': u'Bad Request', u'error': u'invalid_grant'}
I recreated the refresh token, but the problem remains. Please advise.
I know the password of my gmail address. Any recovery code and recovery email address and recovery phone number are not registered. only authenticator and password protected. my phone malfunctioned, i had to do a soft reset. I didn't have an authenticator backup. so i can't login to my gmail account. my important documents were in my drive account. I need access. I wonder if there is a web app so I can bypass or disable gmail authenticator and only login with password? How can I recover? Can this be done with the app?
Hi,
I use this approach to send my emails by msmtp
. However, oauth2.py
stopped to work 08-15-2020.
Traceback (most recent call last):
File "/home/myuser/bin/OAuth2/oauth2.py", line 347, in <module>
main(sys.argv)
File "/home/myuser/bin/OAuth2/oauth2.py", line 307, in main
options.refresh_token)
File "/home/myuser/bin/OAuth2/oauth2.py", line 238, in RefreshToken
response = urllib.urlopen(request_url, urllib.urlencode(params)).read()
File "/usr/lib/python2.7/urllib.py", line 89, in urlopen
return opener.open(url, data)
File "/usr/lib/python2.7/urllib.py", line 217, in open
return getattr(self, name)(url, data)
File "/usr/lib/python2.7/urllib.py", line 445, in open_https
h.endheaders(data)
File "/usr/lib/python2.7/httplib.py", line 1078, in endheaders
self._send_output(message_body)
File "/usr/lib/python2.7/httplib.py", line 894, in _send_output
self.send(msg)
File "/usr/lib/python2.7/httplib.py", line 856, in send
self.connect()
File "/usr/lib/python2.7/httplib.py", line 1295, in connect
HTTPConnection.connect(self)
File "/usr/lib/python2.7/httplib.py", line 833, in connect
self.timeout, self.source_address)
File "/usr/lib/python2.7/socket.py", line 557, in create_connection
for res in getaddrinfo(host, port, 0, SOCK_STREAM):
IOError: [Errno socket error] [Errno -2] Name or service not known
I made a test and run:
$ ./oauth2.py [email protected] --client_id=9876........apps.googleusercontent.com --client_secret=***************************************** --generate_oauth2_token
To authorize token, visit this url and follow the directions:
https://accounts.google.com/o/oauth2/auth?client_id=4485...........apps.googleusercontent.com&redirect_uri=*********************************mail.google.com%2F
I followed that link and made authorization. So, I got the verification code and enter it on the prompt Enter verification code:
After that, I got the same error messages as above:
Traceback (most recent call last):
File "./oauth2.py", line 366, in <module>
main(sys.argv)
File "./oauth2.py", line 345, in main
authorization_code)
File "./oauth2.py", line 228, in AuthorizeTokens
response = urlopen(request_url, data).read()
File "/usr/lib/python2.7/urllib.py", line 89, in urlopen
return opener.open(url, data)
File "/usr/lib/python2.7/urllib.py", line 217, in open
return getattr(self, name)(url, data)
File "/usr/lib/python2.7/urllib.py", line 445, in open_https
h.endheaders(data)
File "/usr/lib/python2.7/httplib.py", line 1078, in endheaders
self._send_output(message_body)
File "/usr/lib/python2.7/httplib.py", line 894, in _send_output
self.send(msg)
File "/usr/lib/python2.7/httplib.py", line 856, in send
self.connect()
File "/usr/lib/python2.7/httplib.py", line 1295, in connect
HTTPConnection.connect(self)
File "/usr/lib/python2.7/httplib.py", line 833, in connect
self.timeout, self.source_address)
File "/usr/lib/python2.7/socket.py", line 557, in create_connection
for res in getaddrinfo(host, port, 0, SOCK_STREAM):
IOError: [Errno socket error] [Errno -2] Name or service not known
myuser@myuser:~/bin/OAuth2$
I have applied the patch for python 3.0 and 2.7 compatibility (here).
Any thoughts?
Thank you
When using oauth2.py I kept getting authentication errors when submitting the code to retrieve a new token. I found it was using https://accounts.google.com/o/oauth2/token
to request tokens vs using https://oauth2.googleapis.com/token
as stated in google's documentation.
I feel there is probably other outdated urls in the script as well.
Hello Google team,
I do not know, how I can send this issue but Google Accounts created with Hotmail addresses "[email protected] like Google Account" (and maybe other Microsoft mail addresses or other mail addresses of the World) can not received the email with the Google Code to confirm that we are the user.
But the blocked alert mail has been received.
I see that it is not new:
Can you solve it?
Thanks in advance.
Storing the json config in $HOME without respecting a user's configured XDG environment violates the spec.
https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html
OAuth2SaslClient refers to OAuth2SaslResponseBuilder, which does not exist. I
had to delete the line referencing it to get the code to compile.
Also, there are a few compilation warnings. The logger is unused and the
URISyntaxException, Logger, and PasswordCallback imports can be removed as they
are runused.
Original issue reported on code.google.com by [email protected]
on 4 Jan 2013 at 7:20
(freescout-helpdesk/freescout#390)
There is no way to use standard PHP IMAP extension https://www.php.net/manual/en/ref.imap.php to connect to Gmail using OAuth?
It will be impossible to access Gmail also via POP3 protocol without OAuth?
I'm trying to implement a service on App Engine that interacts with an Gmail
account using OAuth2, Java 7 and App Engine SDK 1.8.2. The problem being
encountered is via the use of sample code the Security provider does not appear
to be detected on a node although works locally fine. The code provided by the
link before has been modified to be initiated by a servlet with sample code:
import java.io.IOException;
import java.security.Provider;
import java.security.Security;
import java.util.Properties;
import javax.mail.Session;
import javax.mail.URLName;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.code.samples.oauth2.OAuth2SaslClientFactory;
import com.sun.mail.imap.IMAPSSLStore;
import com.sun.mail.imap.IMAPStore;
import com.sun.mail.smtp.SMTPTransport;
public class RunnerServlet extends HttpServlet
{
public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException
{
String email = request.getParameter( "email");
String oauthToken = request.getParameter( "oauthToken");
initialize();
try
{
IMAPStore imapStore = connectToImap("imap.gmail.com",
993,
email,
oauthToken,
true);
System.out.println("Successfully authenticated to IMAP.\n");
SMTPTransport smtpTransport = connectToSmtp("smtp.gmail.com",
587,
email,
oauthToken,
true);
System.out.println("Successfully authenticated to SMTP.");
}
catch( Exception e )
{
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
throw new RuntimeException( e );
}
}
public static final class OAuth2Provider extends Provider {
private static final long serialVersionUID = 1L;
public OAuth2Provider() {
super("Google OAuth2 Provider", 1.0,
"Provides the XOAUTH2 SASL Mechanism");
put("SaslClientFactory.XOAUTH2",
"com.google.code.samples.oauth2.OAuth2SaslClientFactory");
}
}
public static void initialize() {
Security.addProvider(new OAuth2Provider());
}
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);
session.getProperties().put("mail.imaps.sasl.enable", "true");
session.getProperties().put("mail.imaps.sasl.mechanisms", "XOAUTH2");
session.getProperties().put(OAuth2SaslClientFactory.OAUTH_TOKEN_PROP, oauthToken);
final URLName unusedUrlName = null;
IMAPSSLStore store = new IMAPSSLStore(session, unusedUrlName);
final String emptyPassword = "";
store.connect(host, port, userEmail, emptyPassword);
return store;
}
public static SMTPTransport connectToSmtp(String host, int port,
String userEmail, String oauthToken, boolean debug)
throws Exception {
Properties props = new Properties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.starttls.required", "true");
props.put("mail.smtp.sasl.enable", "true");
props.put("mail.smtp.sasl.mechanisms", "XOAUTH2");
props.put(OAuth2SaslClientFactory.OAUTH_TOKEN_PROP, oauthToken);
Session session = Session.getInstance(props);
session.setDebug(debug);
final URLName unusedUrlName = null;
SMTPTransport transport = new SMTPTransport(session, unusedUrlName);
// If the password is non-null, SMTP tries to do AUTH LOGIN.
final String emptyPassword = null;
transport.connect(host, port, userEmail, emptyPassword);
return transport;
}
}
The IMAP debug trace is:
DEBUG IMAPS: mail.imap.fetchsize: 16384
DEBUG IMAPS: mail.imap.ignorebodystructuresize: false
DEBUG IMAPS: mail.imap.statuscachetimeout: 1000
DEBUG IMAPS: mail.imap.appendbuffersize: -1
DEBUG IMAPS: mail.imap.minidletime: 10
DEBUG IMAPS: enable SASL
DEBUG IMAPS: SASL mechanisms allowed: XOAUTH2
DEBUG IMAPS: trying to connect to host "imap.gmail.com", port 993, isSSL true
* OK Gimap ready for requests from xxx.xxx.xxx.xxx ZZZZZZZZZ
A0 CAPABILITY
* CAPABILITY IMAP4rev1 UNSELECT IDLE NAMESPACE QUOTA ID XLIST CHILDREN X-GM-EXT-1 XYZZY
A0 OK Thats all she wrote! ZZZZZZZZZ
DEBUG IMAPS: AUTH: XOAUTH
DEBUG IMAPS: AUTH: XOAUTH2
DEBUG IMAPS: protocolConnect login, host=imap.gmail.com, [email protected], password=<non-null>
DEBUG IMAPS: SASL authentication command trace suppressed
DEBUG IMAPS: SASL Mechanisms:
DEBUG IMAPS: XOAUTH2
DEBUG IMAPS:
DEBUG IMAPS: No SASL support
DEBUG IMAPS: SASL authentication failed
DEBUG IMAPS: LOGIN command trace suppressed
DEBUG IMAPS: LOGIN command result: A1 NO Empty username or password. ZZZZZZZZZ
DEBUG IMAPS: trying to connect to host "imap.gmail.com", port 993, isSSL true
* OK Gimap ready for requests from xxx.xxx.xxx.xxx YYYYYYYYYY
A0 CAPABILITY
* CAPABILITY IMAP4rev1 UNSELECT IDLE NAMESPACE QUOTA ID XLIST CHILDREN X-GM-EXT-1 XYZZY SASL-IR AUTH=XOAUTH AUTH=XOAUTH2
A0 OK Thats all she wrote! YYY
DEBUG IMAPS: AUTH: XOAUTH
DEBUG IMAPS: AUTH: XOAUTH2
DEBUG IMAPS: protocolConnect login, host=imap.gmail.com, [email protected], password=<non-null>
DEBUG IMAPS: SASL authentication command trace suppressed
DEBUG IMAPS: SASL Mechanisms:
DEBUG IMAPS: XOAUTH2
DEBUG IMAPS:
DEBUG IMAPS: No SASL support
DEBUG IMAPS: SASL authentication failed
DEBUG IMAPS: LOGIN command trace suppressed
DEBUG IMAPS: LOGIN command result: A1 NO Empty username or password. YYYYYYYYYY
java.lang.RuntimeException: javax.mail.AuthenticationFailedException: Empty username or password. YYYYYYYYYY
This problem only occurs on a deployed node. Ensured that the provider was
correct path and installed and using the latest versions of App Engine SDK that
facilitates the IMAP and SMTP sockets. Triggering has been attempted via sample
servlet and task on task queue. The expected result would be no exception and
"Successfully authenticated to IMAP" appearing as output.
Thank you for assistance in advance.
Original issue reported on code.google.com by [email protected]
on 29 Jul 2013 at 12:56
Hi there,
We are trying to test this code according to the description in the wiki, but it is giving us a syntax error:
print 'Missing options: %s' % ' '.join(missing) ^ SyntaxError: invalid syntax
Any thoughts?
Due to a bug in the implementation of JavaMail that is bundled with the current
version of AppEngine, the property settings passed into the
Session.getInstance() method are not properly honored.
The workaround is to get the Properties object and set the values again *post*
creation (the initial puts are redundant but left just in case).
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);
session.getProperties().sProps.put("mail.imaps.sasl.enable", "true");
session.getProperties().sProps.put("mail.imaps.sasl.mechanisms", "XOAUTH2");
session.getProperties().sProps.put(OAuth2SaslClientFactory.OAUTH_TOKEN_PROP, oauthToken);
NOTE: This is only necessary when deploying this to appEngine. This bug is
fixed in JavaMail 1.4.5 and beyond.
Original issue reported on code.google.com by [email protected]
on 22 Jun 2013 at 12:43
I made a note stating the pre-requisite step to take before attempting to use
this example.
Original issue reported on code.google.com by [email protected]
on 9 Dec 2012 at 10:45
Attachments:
Hi there,
I am not able to get oauth2.py library working in python 3, any chance it will get updated?
The page shouldn't display E_NOTICE on the first load.
Original issue reported on code.google.com by [email protected]
on 12 Feb 2014 at 1:42
Attachments:
Hello,
I'm trying to generate a token with the oauth2 python script, but I have this error below :
python oauth2.py
File "oauth2.py", line 34
oauth2 --user=[email protected]
^
SyntaxError: invalid syntax
I tried with python, python2, and python3.
With python 3 I have this error 👍
File "oauth2.py", line 317
print 'Access Token: %s' % response['access_token']
Thanks in advance for your help;
Best regards,
Is this expected to work anymore? It seems that policies have changed and the urn:ietf:wg:oauth:2.0:oob
URL is no longer valid. So…how is a desktop application supposed to communicate with the GMail API anymore?
Python2 is long deprecated, how can we use this script with Python3?
for starters:
✖1 ❯ oauth2 --generate_oauth2_token
File "/Users/rosenmanl/bin/oauth2", line 297
print 'Missing options: %s' % ' '.join(missing)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
SyntaxError: Missing parentheses in call to 'print'. Did you mean print(...)?
Does this not work for non-GSuite accounts? I made the app and client ID. However, when I go through and get a token, all I ever get is a 401. There's no error message in the body of the response.
Has something changed that needs updated in the script?
What steps will reproduce the problem?
1. Give my access token (I get this token from Mobile App)
2. Submit and get email successfully.
3. But after a minutes, I submit again and get a result as "login fail..."
I thinks your code don't refresh a given access token automatically to login
again. Can you give me an example how to do it?
Original issue reported on code.google.com by [email protected]
on 31 Oct 2014 at 2:22
I am trying to test the PHP sample code, but always get a "Failed to login"
error.
* I have a valid access token, which I can use to access my google profile
information
* I asked for email access in my oauth scope
(https://mail.google.com/mail/feed/atom/)
* I asked for offline access when granting permission (access_type=offline)
* I have IMAP enabled in my Gmail account
Is there something I'm missing?
Original issue reported on code.google.com by [email protected]
on 12 Oct 2012 at 7:42
I propose setting up a local HTTP server to grab the OAuth2 authorization token directly (instead of going through https://oauth2.dance). There are a few reasons:
oauth2.dance
is not Google (though maybe it was) and I prefer not to trust one more company.I understand that many non-Google OAuth2 services seem to have issues about HTTP even for localhost
, and there were security concerns when you don't trust all the local programs (e.g., Android), but none of these concerns seem to apply to the primary use case of sendgmail
.
Related issue: #49 (OOB no longer works)
Please help
I've been struggling for months to find the correct solution to using XOAUTH2 authentication when sending emails via SMTP.
The only complication is that some of the emails are generated by overnight (eg batch) processes, so we can't use a redirect_uri ever.
I've found examples that work with IMAP (like this one) but nothing that works with SMTP that can be navigated completely via an API without any human intervention.
a) Is this possible?
b) Does this exist? Where?
Any pointers to some sample code would be helpful.
Cheers
Murray
The wiki includes the comment (on https://github.com/google/gmail-oauth2-tools/wiki/OAuth2DotPyRunThrough):
"To use OAuth2, you must have registered your application through the Google APIs Console. Registration is explained in Using OAuth 2.0 to Access Google APIs."
Unfortuntately, neither of the links actually explains what needs to be registered where nor (presumably) how to obtain the 'client-id' token used in the examples on the page.
There is lots of stuff about setting up GCP accounts/projects, but nothing about getting a client-id. Additionally there is lots of documentation on how to use third party apps with the IMAP interface, but nothing (that I can find) on how authentication is now meant to work with IMAP on gmail for a simple program.
Isn't the withdrawal of an authentication mechanism quite a serious security event as it severely hits the availability (as in the mnemonic of Confidentiality, Integrity, Availability for Security) of the service?
Acc
Fix XSS in displayForm()
Original issue reported on code.google.com by [email protected]
on 12 Feb 2014 at 1:37
gmail-oauth2-tools/go/sendgmail/main.go
Line 98 in 912b0c1
fmt.Println(authCodeURL + "&access_type=offline") // hack to obtain a refresh token
but all I get is an access token. Only when I add &prompt=consent
too beside of the access token a refresh token is returned.
Is this desired?
This allows using a far more limited OAuth token. sendgmail does not need the ability to delete email, for example.
This doesn’t matter on most systems, where sendgmail runs with the same privilege as the user’s browser. However, it does matter for QubesOS users who want to use sendgmail from a different VM.
I got my client_id and client_secret from google, and when I run in the console following command:
python oauth2.py --client_id=##my_id --client_secret=##my_secret
I got syntax error:
File "oauth2.py", line 297
print 'Missing options: %s' % ' '.join(missing)
^
SyntaxError: invalid syntax
How to fix this?
Nothing
Original issue reported on code.google.com by [email protected]
on 29 Mar 2015 at 3:25
Attachments:
Is there some way to get the sendgmail
tool to work for a G Suite account? The tool seems to require a "@gmail.com" account. How can I get git send-email
to work with a G Suite account without creating an "App-specific password"?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.