skip to Main Content

I am writing a simple Twitter authentication flow with a REST API setup. Client side is just plain javascript/Vue code – there is no server-side rendering. This consumes a backend REST API built with Django Rest Framework, using tweepy library to wrap the Twitter API.

I have the authentication working, with the following steps:

  1. User clicks a ‘log in to twitter’ button, which fires a call to my backend API /get-url/
  2. API calls Twitter’s get_authorization_url (using my Twitter app credentials), gets the token, and returns this redirection URL to the client
  3. Client redirects user to the Twitter URL to complete authentication
  4. On callback, client passes all params thru to backend API endpoint
  5. API gets token and secret; creates a tweepy API with user auth; and calls verify_credentials
  6. If everything worked fine, we create a user account in a Django database tied to the Twitter user, storing their token and secret; logs the user in with a JWT; and returns a 200 success with token.
  7. Front end deals with doing JWT token refreshing etc; but otherwise uses this for authentication on the rest of the API.

However, there is one bit I’m stumped on: The Twitter docs suggest that in my step 2, I should save the request_token so that, on step 5, I can check it matches what is returned from the Twitter API (https://developer.twitter.com/en/docs/authentication/guides/log-in-with-twitter).

The tweepy docs example (http://docs.tweepy.org/en/latest/auth_tutorial.html) suggests storing it in the session, then on callback checking them and deleting from the session.

However, this doesn’t make sense (at least to me) in a REST API setup like mine. I’m stumped on how to temporarily store this on the server so that on callback I can check its value – prior to the redirect, I know nothing about the user to "tie" this token to, there is no user record to store in the database.

All I can think to do is for the API on (2) to return it to the client; then it can be stored in a cookie before redirect; then on callback, pass it back to the server… but this seems very convoluted and doing it all in plain text I assume nullifies the value of doing this extra check.

Hopefully I’m missing something obvious here.

2

Answers


  1. Have you tried using python-social-auth library?

    from_the_docs: twitter is in supported Authentication Backends.

    Login or Signup to reply.
  2. You can try letting the user register with basic details, then have a ‘link to Twitter’ button that shows they have to activate their twitter connection to do anything else on your web app

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search