0

I have code something like below -

app = Flask(__name__)


# access token
access_token = None


@app.route('/getcode')
def get_authorization_url():
    oauth = OAuth2Session(client_id, redirect_uri=redirect_uri, scope=scope)
    authorization_url, _state = oauth.authorization_url(authorization_base_url, access_type="authorization_code")
    print('authorization_url')
    print(authorization_url)
    return redirect(authorization_url)


@app.route('/')
def callback():
    global access_token
    oauth = OAuth2Session(client_id, redirect_uri=redirect_uri, scope=scope)
    token = oauth.fetch_token(token_url, authorization_response=request.url, client_secret=client_secret)
    access_token = token['access_token']
    print('access token is:', access_token)

    ## we will be shutting down the server after getting access_token
    ## the thread created here is copied in if __name__ == '__main__' block
    ## and will run after closing the server

    # th = threading.Thread(target=data_from_resource_server, args=(access_token,))
    # th.start()

    func = request.environ.get('werkzeug.server.shutdown')
    if func:
        print('stoping server')
        func()


    return 'see terminal for logs'


if __name__ == '__main__':
    app.secret_key = 'example'
    app.env = 'development'
    print()
    print('Open this url in browser:', 'http://127.0.0.1/getcode', end='\n\n')

    app.run(host='127.0.0.1', port='80')

    print('server stopped')

    ## got access_token, closed the server, now running ray integration code
    if access_token:
        th = threading.Thread(target=data_from_resource_server, args=(access_token,))
        th.start()

Here when app.run(host='127.0.0.1', port='80') runs gives me URL - http://127.0.0.1/getcode. I need to mannually open enter username and password and again then one more window comes to enter YOB, which then give me something like -

127.0.0.1 - - [04/May/2021 21:20:23] "GET /**getcode?code=G7h_QL0Cpo3kEqyyNBZ68DTX3JhQ_6E6sl_Sk1x5iBc.oG4JFQiKyZGupTuJ-bV6qE9lA**&scope=orders&state=M6hdb7EJxgNKkuBqbihg1SKaUGAJ7W HTTP/1.1" 302  

Here My question is there a way to avoid doing this manually opening the browser and enter credentials and get the code. can we parse the entire thing in python?

keerthan kumar
  • 332
  • 7
  • 25

1 Answers1

0

Sounds like a job for Selenium! It can open a web browser and parse the required details for you.

Run the following code after starting the server

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

url = 'http://127.0.0.1/getcode'
driver = webdriver.Firefox()  # (Or Chrome())
driver.get(url)

username = driver.find_element_by_id("username")
password = driver.find_element_by_id("password")

# uncomment this code if your text boxes have pre-populated text
#username.clear()
#password.clear()

username.send_keys("YourUsername") # change this to your username
password.send_keys("PassworD")     # change this to your password
driver.find_element_by_name("submit").click()

# we can implicitly wait before the page loads
driver.implicitly_wait(2)

Now, this handles the first part of your question i.e. automate the login process. Now I'm not sure what's your next goal but I assume you want the code variable in the URL, which I assume is returned by the OAuth2 funtion.

We can achieve this by simply getting the URL and parsing for the code variable

To get the URL

current_url = driver.current_url;

Now, you can simply parse the URL using urlparse.

import urllib.parse as urlparse
from urllib.parse import parse_qs

parsed = urlparse.urlparse(current_url)
OAuth_code = parse_qs(parsed.query)['code']

Some sources you can refer:

  1. https://medium.com/swlh/automate-data-collection-with-selenium-in-python-246a051206e2
  2. Fill username and password using selenium in python
  3. Find URL after clicking a link
  4. https://stackoverflow.com/a/5075477/11029298
  5. https://selenium-python.readthedocs.io/getting-started.html
greysou1
  • 346
  • 3
  • 8
  • is there any way to achieve this without selenium? – keerthan kumar May 15 '21 at 06:19
  • an oauth code is generated only after you accept the server's prompt asking if you would like to authorize the application’s request. i.e. login in your case. There really seems to be no other way that I know of that can bypass this [Authorization Code Flow](https://developer.okta.com/blog/2018/04/10/oauth-authorization-code-grant-type#the-authorization-code-flow). – greysou1 May 16 '21 at 09:13