Code Monkey home page Code Monkey logo

gmail-oauth2-tools's Introduction

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].

gmail-oauth2-tools's People

Contributors

daksh avatar dependabot[bot] avatar djnicolson avatar junyer avatar ssalbiz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

gmail-oauth2-tools's Issues

Cannot generate token

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

API probably doesn't send "refresh_token"s anymore.

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?

oauth2.py: Bad Request error, invalid grant

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.

How to Authenticator bypass or disable for google account

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?

oauth2.py stopped to work - urllib.py, httplib.py and socket.py issues

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

oauth2.py uses outdated urls

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.

A problem with hotmail.com Google Accounts "[email protected] like Google Account" do not have the code email to verify

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.

Remove reference to OAuth2SaslResponseBuilder

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

IMAP using OAuth2 on App Engine

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

Syntax Error: Missing Options Produces Syntax Error

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?

The java code sample does not work in AppEngine 1.8.x for Gmail/IMAP

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

Python: SyntaxError: invalid syntax - Generate a Token

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,

GMail refresh token retrieval no longer working

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?

Python3 version?

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(...)?

401 errors

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?

Access token don't refresh

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

PHP Sample Code Not Working?

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

sendgmail: consider using localhost to get the oauth2 token

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:

  1. No more copy-pasting is needed for the token.
  2. The domain registrar oauth2.dance is not Google (though maybe it was) and I prefer not to trust one more company.
  3. It is trivial to set up an ephemeral HTTP server in Go.
  4. The change will slightly simplify the procedure to obtain a new client ID.

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)

SMTP with XOAUTH2

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

Unclear how to register an application, establish a client-id

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?

B

Acc

sendgmail: use the GMail API instead of SMTP

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.

Syntax errot

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?

sendgmail support for G Suite accounts

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"?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.