[Django]-Django Social Auth w/ Twitter: HTTP 401 Error (Unauthorized)

13👍

First, stop what you’re doing–you need to go on Twitter and reset your keys for the app because you appear to have placed your TWITTER_APP_KEY and TWITTER_APP_SECRET in your question. Update your settings.py with your new keys.

Ok? Done? Good. Assuming you’ve got the proper auth keys in your application:

Problem number 1: As far as I recall off the top of my head, twitter does not allow oauth requests from anything BUT port 80. Django’s dev server 8000 is going to cause you problems (other services work just fine though).

To test locally, we’re going to do the following things:

  1. Remap your hosts file for local testing:
    If you’re running under Windows, update your HOSTS file %WINDIR%\system32\drivers\etc\hosts (on linux, it’s /etc/hosts/) and map your site’s domain name to 127.0.0.1.

    This is helpful when you’re testing code locally that relies on external callbacks. It doesn’t always matter (facebook is MORE than happy to callback your app on localhost:8000 .. twitter, as I recall, is not).

  2. Start django development server on port 80.

    python manage.py runserver 0.0.0.0:80

  3. Open your application settings on twitter’s website. Place your real domain in the website field.

  4. In the ‘Callback URL’ place a DUMMY url on your domain. This setting does NOT matter as long as a valid url is in this field. I like to use http://whateveryoururlis.com/dummy-url. This information can be found here: http://django-social-auth.readthedocs.org/en/latest/backends/twitter.html .. I assume this has to be a url under your domain, I’ve never tried it with a completely random domain.

  5. Check ‘Allow this application to be used to sign in with twitter’

  6. Open your favorite browser and navigate to your real domain name (which will resolve to django’s development server on your local machine since we remapped the host file in step 1). You should now be able to login with twitter.

As a point of interest, django social auth is depreciated and the author recommends migrating to python-social-auth, which supports django.

Lastly.. I just realized this question was from august.. but someone posted an answer yesterday, which prompted me to write all this before realizing it’s such an old question. Hope it helps someone though!

2👍

Maybe, you set wrong callback URL on your Twitter application settings.
Set http://127.0.0.1:8000/ as callback URL when you run in local environment.

See this: http://c2journal.com/2013/01/24/social-logins-with-django/

-2👍

Double check our API keys and the settings for the App you added to your Twitter account. It looks like twitter is denying you access because it cannot validate the details.

Leave a comment