def authorize(self): # TODO : reafactorize with REDIRECT_URI if os.path.exists(self.auth_file): access_token = self.get_access_token_from_file() else: httpd = ClientRedirectServer(("localhost", 8888), ClientRedirectHandler) webbrowser.open(self.get_auth_url()) httpd.handle_request() access_token, user_id, url_state = self.flow.finish(httpd.query_params) self.build(access_token)
def authorize(self): if os.path.exists(self.auth_file): access_token, refresh_token = self.get_tokens_from_file() self.oauth._access_token = access_token self.oauth._refresh_token = refresh_token else: httpd = ClientRedirectServer(("localhost", 8888), ClientRedirectHandler) webbrowser.open(self.get_auth_url()) httpd.handle_request() self.oauth.authenticate(httpd.query_params['code']) self.build()
def CustomLocalWebserverAuth(authorize_url, host_name='localhost', port_numbers=None): """Authenticate and authorize from user by creating local web server and retrieving authentication code. This function is not for web server application. It creates local web server for user from standalone application. :param host_name: host name of the local web server. :type host_name: str. :param port_numbers: list of port numbers to be tried to used. :type port_numbers: list. :returns: str -- code returned from local web server :raises: AuthenticationRejected, AuthenticationError """ if port_numbers is None: port_numbers = [8080, 8090] # Mutable objects should not be default # values, as each call's changes are global. success = False port_number = 0 for port in port_numbers: port_number = port try: httpd = ClientRedirectServer((host_name, port), ClientRedirectHandler) except socket.error as e: pass else: success = True break if success: oauth_callback = 'http://%s:%s/' % (host_name, port_number) else: print('Failed to start a local web server. Please check your firewall') print('settings and locally running programs that may be blocking or') print('using configured ports. Default ports are 8080 and 8090.') raise AuthenticationError() #webbrowser.open(authorize_url, new=1, autoraise=True) webbrowser.open_new_tab(authorize_url) print( 'Your browser has been opened to authorize access to your Google Drive Colab:' ) print() print(' ' + authorize_url) print() httpd.handle_request() if 'error' in httpd.query_params: print('Authentication request was rejected') raise AuthenticationRejected('User rejected authentication') if 'code' in httpd.query_params: return httpd.query_params['code'] else: print('Failed to find "code" in the query parameters of the redirect.') print('Try command-line authentication') raise AuthenticationError('No code found in redirect')
def authorize(self): # TODO : reafactorize with REDIRECT_URI if os.path.exists(self.auth_file): access_token = self.get_access_token_from_file() else: httpd = ClientRedirectServer(("localhost", 8888), ClientRedirectHandler) webbrowser.open(self.get_auth_url()) httpd.handle_request() access_token, user_id, url_state = self.flow.finish( httpd.query_params) self.build(access_token)
def authorize(client_id, client_secret, scope, user_agent, credentials_path): oauth2_flow = OAuth2WebServerFlow(client_id=client_id, client_secret=client_secret, scope=scope, user_agent=user_agent) http = httplib2.Http(timeout=5) _log.info("loading credentials...") storage = Storage(credentials_path) credentials = storage.get() if credentials is None or credentials.invalid: _log.info("authorization required, requesting token...") try: # prepare response listener server_address = ("localhost", get_free_port()) httpd = ClientRedirectServer(server_address, ClientRedirectHandler) httpd.timeout = 3 * 60 # open authorize url oauth2_flow.redirect_uri = "http://{}:{}/".format(server_address[0], server_address[1]) authorize_url = oauth2_flow.step1_get_authorize_url() webbrowser.open(authorize_url, new=1, autoraise=True) # wait for response httpd.handle_request() # handle errors if "code" in httpd.query_params: token = httpd.query_params["code"] elif not httpd.query_params: raise TimeoutError("no response from server") elif "error" in httpd.query_params: raise ConnectionRefusedError(httpd.query_params["error"]) else: raise ConnectionAbortedError("server did not return authorization code") credentials = oauth2_flow.step2_exchange(token, http=http) except Exception as e: _log.error("authorization has failed: {0}".format(e)) raise _log.info("saving credentials...") credentials.set_store(storage) storage.put(credentials) _log.info("authorization successful.") else: _log.info("no authorization required, using saved token...") return credentials.authorize(http)
def authenticate(self, no_browser=False): if no_browser: httpd = None redirect_uri = 'urn:ietf:wg:oauth:2.0:oob' else: httpd = ClientRedirectServer(('localhost', 0), ClientRedirectHandler) redirect_uri = 'http://localhost:%d/' % httpd.server_port flow = OAuth2WebServerFlow(client_id=self.CLIENT_ID, client_secret=self.CLIENT_SECRET, scope=self.SCOPE, redirect_uri=redirect_uri) auth_url = flow.step1_get_authorize_url() if httpd is None: print('Open the following URL in a browser:\n\n%s' % auth_url) code = input('Enter verification code: ').strip() else: webbrowser.open(auth_url) print('Your browser has been opened to visit:\n\n%s\n' % auth_url) print('If your browser is on a different machine, then exit ' 'and re-run with the --no-browser command line option.') try: httpd.handle_request() finally: httpd.server_close() if 'error' in httpd.query_params: raise GAPIError('Authentication request was rejected.') if 'code' in httpd.query_params: code = httpd.query_params['code'] else: raise GAPIError('Failed to retreive verification code. ' 'Try running with --no-browser.') credentials = flow.step2_exchange(code) self.config.update_credentials(credentials)
def run(flow, storage, http=None): """Core code for a command-line application. The run() function is called from your application and runs through all the steps to obtain credentials. It takes a Flow argument and attempts to open an authorization server page in the user's default web browser. The server asks the user to grant your application access to the user's data. If the user grants access, the run() function returns new credentials. The new credentials are also stored in the Storage argument, which updates the file associated with the Storage object. It presumes it is run from a command-line application and supports the following flags: --auth_host_name: Host name to use when running a local web server to handle redirects during OAuth authorization. (default: 'localhost') --auth_host_port: Port to use when running a local web server to handle redirects during OAuth authorization.; repeat this option to specify a list of values (default: '[8080, 8090]') (an integer) --[no]auth_local_webserver: Run a local web server to handle redirects during OAuth authorization. (default: 'true') Since it uses flags make sure to initialize the gflags module before calling run(). Args: flow: Flow, an OAuth 2.0 Flow to step through. storage: Storage, a Storage to store the credential in. http: An instance of httplib2.Http.request or something that acts like it. Returns: Credentials, the obtained credential. """ logging.warning( 'This function, oauth2client.tools.run(), and the use of ' 'the gflags library are deprecated and will be removed in a future ' 'version of the library.') if FLAGS.auth_local_webserver: success = False port_number = 0 for port in FLAGS.auth_host_port: port_number = port try: httpd = ClientRedirectServer((FLAGS.auth_host_name, port), ClientRedirectHandler) except socket.error as e: pass else: success = True break FLAGS.auth_local_webserver = success if not success: print( 'Failed to start a local webserver listening on either port 8080' ) print( 'or port 9090. Please check your firewall settings and locally' ) print( 'running programs that may be blocking or using those ports.') print() print( 'Falling back to --noauth_local_webserver and continuing with') print('authorization.') print() if FLAGS.auth_local_webserver: oauth_callback = 'http://%s:%s/' % (FLAGS.auth_host_name, port_number) else: oauth_callback = client.OOB_CALLBACK_URN flow.redirect_uri = oauth_callback authorize_url = flow.step1_get_authorize_url() if FLAGS.auth_local_webserver: webbrowser.open(authorize_url, new=1, autoraise=True) print('Your browser has been opened to visit:') print() print(' ' + authorize_url) print() print('If your browser is on a different machine then exit and re-run') print('this application with the command-line parameter ') print() print(' --noauth_local_webserver') print() else: print('Go to the following link in your browser:') print() print(' ' + authorize_url) print() code = None if FLAGS.auth_local_webserver: httpd.handle_request() if 'error' in httpd.query_params: sys.exit('Authentication request was rejected.') if 'code' in httpd.query_params: code = httpd.query_params['code'] else: print( 'Failed to find "code" in the query parameters of the redirect.' ) sys.exit('Try running with --noauth_local_webserver.') else: code = raw_input('Enter verification code: ').strip() try: credential = flow.step2_exchange(code, http=http) except client.FlowExchangeError as e: sys.exit('Authentication has failed: %s' % e) storage.put(credential) credential.set_store(storage) print('Authentication successful.') return credential
def run(flow, storage, http=None): """Core code for a command-line application. The ``run()`` function is called from your application and runs through all the steps to obtain credentials. It takes a ``Flow`` argument and attempts to open an authorization server page in the user's default web browser. The server asks the user to grant your application access to the user's data. If the user grants access, the ``run()`` function returns new credentials. The new credentials are also stored in the ``storage`` argument, which updates the file associated with the ``Storage`` object. It presumes it is run from a command-line application and supports the following flags: ``--auth_host_name`` (string, default: ``localhost``) Host name to use when running a local web server to handle redirects during OAuth authorization. ``--auth_host_port`` (integer, default: ``[8080, 8090]``) Port to use when running a local web server to handle redirects during OAuth authorization. Repeat this option to specify a list of values. ``--[no]auth_local_webserver`` (boolean, default: ``True``) Run a local web server to handle redirects during OAuth authorization. Since it uses flags make sure to initialize the ``gflags`` module before calling ``run()``. Args: flow: Flow, an OAuth 2.0 Flow to step through. storage: Storage, a ``Storage`` to store the credential in. http: An instance of ``httplib2.Http.request`` or something that acts like it. Returns: Credentials, the obtained credential. """ logging.warning('This function, oauth2client.tools.run(), and the use of ' 'the gflags library are deprecated and will be removed in a future ' 'version of the library.') if FLAGS.auth_local_webserver: success = False port_number = 0 for port in FLAGS.auth_host_port: port_number = port try: httpd = ClientRedirectServer((FLAGS.auth_host_name, port), ClientRedirectHandler) except socket.error as e: pass else: success = True break FLAGS.auth_local_webserver = success if not success: print('Failed to start a local webserver listening on either port 8080') print('or port 9090. Please check your firewall settings and locally') print('running programs that may be blocking or using those ports.') print() print('Falling back to --noauth_local_webserver and continuing with') print('authorization.') print() if FLAGS.auth_local_webserver: oauth_callback = 'http://%s:%s/' % (FLAGS.auth_host_name, port_number) else: oauth_callback = client.OOB_CALLBACK_URN flow.redirect_uri = oauth_callback authorize_url = flow.step1_get_authorize_url() if FLAGS.auth_local_webserver: webbrowser.open(authorize_url, new=1, autoraise=True) print('Your browser has been opened to visit:') print() print(' ' + authorize_url) print() print('If your browser is on a different machine then exit and re-run') print('this application with the command-line parameter ') print() print(' --noauth_local_webserver') print() else: print('Go to the following link in your browser:') print() print(' ' + authorize_url) print() code = None if FLAGS.auth_local_webserver: httpd.handle_request() if 'error' in httpd.query_params: sys.exit('Authentication request was rejected.') if 'code' in httpd.query_params: code = httpd.query_params['code'] else: print('Failed to find "code" in the query parameters of the redirect.') sys.exit('Try running with --noauth_local_webserver.') else: code = input('Enter verification code: ').strip() try: credential = flow.step2_exchange(code, http=http) except client.FlowExchangeError as e: sys.exit('Authentication has failed: %s' % e) storage.put(credential) credential.set_store(storage) print('Authentication successful.') return credential
import socket import http.server from oauth2client.tools import ClientRedirectServer, ClientRedirectHandler port_number = 0 host_name = 'localhost' for port_number in range(8080,10000): try: httpd = ClientRedirectServer((host_name, port_number), ClientRedirectHandler) except ValueError as err: print ("socket error: " + str(err)) pass else: print ("The server is running on: port " + str(port_number)) print ("and host_name " + host_name) httpd.serve_forever() break