Mastering Authentication with Requests OAuthlib for Python Developers

The Requests-OAuthlib library is a versatile tool designed to simplify the process of connecting Python applications to third-party APIs that use OAuth for authorization. With seamless integration of the requests library and OAuth working together, it offers a user-friendly interface to handle OAuth 1 and OAuth 2 tokens. Whether you’re integrating with APIs like Google, Twitter, or GitHub, this library streamlines token management and API authentication.

In this blog post, we’ll dive deep into “requests-oauthlib”, learn how to authenticate with OAuth 1 and OAuth 2, and explore step-by-step coding examples of using this library with the APIs. Let’s also build a practical application example at the end!

Installing Requests-OAuthlib

Before we get started, you need to install the library:

  pip install requests-oauthlib

Authenticating with OAuth 1

OAuth 1 is commonly used for older APIs like Twitter. Here’s an example of accessing a resource using OAuth 1:

  from requests_oauthlib import OAuth1Session

  # Replace the below values with your credentials
  consumer_key = "your_consumer_key"
  consumer_secret = "your_consumer_secret"
  access_token = "your_access_token"
  access_token_secret = "your_access_token_secret"

  # Create an OAuth1Session
  oauth = OAuth1Session(
      consumer_key,
      client_secret=consumer_secret,
      resource_owner_key=access_token,
      resource_owner_secret=access_token_secret
  )

  # Access a protected resource
  response = oauth.get('https://api.twitter.com/1.1/statuses/user_timeline.json')
  print(response.json())

Authenticating with OAuth 2

OAuth 2 is simpler and used by most modern APIs. Here’s an example of using the library with OAuth 2:

  from requests_oauthlib import OAuth2Session

  client_id = "your_client_id"
  client_secret = "your_client_secret"
  authorization_base_url = 'https://provider.com/oauth/authorize'
  token_url = 'https://provider.com/oauth/token'

  # Redirect user to provider for authorization
  oauth = OAuth2Session(client_id)
  authorization_url, state = oauth.authorization_url(authorization_base_url)
  print('Please go to %s and authorize access.' % authorization_url)

  # Get the authorization response URL from the user
  redirect_response = input('Paste the full redirect URL here: ')

  # Fetch the access token
  token = oauth.fetch_token(
      token_url,
      authorization_response=redirect_response,
      client_secret=client_secret
  )

  # Access protected resources
  response = oauth.get('https://provider.com/api/resource')
  print(response.json())

Using Refresh Tokens

Some OAuth 2 workflows provide refresh tokens to keep your access scope active. Here’s how to use them:

  token = {
      'access_token': 'existing_access_token',
      'refresh_token': 'your_refresh_token',
      'token_type': 'Bearer',
      'expires_in': '-30'  # Simulate expired token
  }

  extra = {
      'client_id': client_id,
      'client_secret': client_secret,
  }

  # Auto-refreshing token functionality
  oauth = OAuth2Session(client_id, token=token, auto_refresh_kwargs=extra,
                        auto_refresh_url=token_url, token_updater=lambda x: None)

  # Access protected resources
  response = oauth.get('https://provider.com/api/resource')
  print(response.json())

A Practical Application Example

Let’s create a real-world example: a GitHub Repository Lister. This app will authenticate with GitHub using OAuth 2 and fetch repositories for the authenticated user.

  from requests_oauthlib import OAuth2Session

  CLIENT_ID = 'your_github_app_client_id'
  CLIENT_SECRET = 'your_github_app_client_secret'
  AUTH_URL = 'https://github.com/login/oauth/authorize'
  TOKEN_URL = 'https://github.com/login/oauth/access_token'

  # Step 1: Redirect user to authorize the app
  github = OAuth2Session(CLIENT_ID)
  authorization_url, _ = github.authorization_url(AUTH_URL)
  print(f'Please go to {authorization_url} and authorize access.')

  # Step 2: Receive the callback from the user
  redirect_response = input('Paste the full redirect URL here: ')

  # Step 3: Retrieve the access token
  token = github.fetch_token(
      TOKEN_URL,
      authorization_response=redirect_response,
      client_secret=CLIENT_SECRET
  )

  # Step 4: Fetch user's repositories
  response = github.get('https://api.github.com/user/repos')
  repos = response.json()

  print('Your Repositories:')
  for repo in repos:
      print(f"- {repo['name']}: {repo['html_url']}")

The Requests-OAuthlib library provides convenience when dealing with complicated OAuth workflows. Whether you’re accessing APIs for personal projects or professional applications, mastering this library ensures you secure data seamlessly and efficiently.

Leave a Reply

Your email address will not be published. Required fields are marked *