python-social-auth and github, I have this error "The redirect_uri MUST match the registered callback URL for this application"

Question:

I’m using python-social-auth on a project to authenticate the user with Github.
I need to redirect the user depending on the link they use. To do that I’m using the next attribute on the url, and I didn’t declare any redirect url on my github app neither in my django settings.

This is the href attribute I’m using for my link : {% url 'social:begin' 'github' %}?next={% url 'apply' j.slug %}

And the first time I click on it, I’m getting redirected to my homepage with this error in the url field : http://127.0.0.1:8000/?error=redirect_uri_mismatch&error_description=The+redirect_uri+MUST+match+the+registered+callback+URL+for+this+application.&error_uri=https%3A%2F%2Fdeveloper.github.com%2Fv3%2Foauth%2F%23redirect-uri-mismatch&state=Ui1EOKTHDhOkNJESI5RTjOCDEIdfFunt

But after first time the link work.

I don’t know where is the problem, I hope someone can help me. Thanks

Asked By: Uhsac

||

Answers:

This library uses OAuth for GitHub authentication.

You must provide a callback URL, because the OAuth process causes the user’s browser to actually leave your site as part of the authentication process. The callback URL that you send to GitHub is used to redirect users back to your site.

It looks like Python Social Auth handles some of this for you, though (emphasis mine):

GitHub

Github works similar to Facebook (OAuth).

  • Register a new application at GitHub Developers, set the callback URL to http://example.com/complete/github/ replacing example.com with your domain.

  • Fill App Id and App Secret values in the settings:

    SOCIAL_AUTH_GITHUB_KEY = ''
    SOCIAL_AUTH_GITHUB_SECRET = ''
    
  • Also it’s possible to define extra permissions with:

    SOCIAL_AUTH_GITHUB_SCOPE = [...]
    

The tricky bit is getting this to work on your development machine.

Setting your domain to 127.0.0.1 in your hosts file should work, something like this

127.0.0.1   example.com

but make sure to comment this like out once you move into production!

You may also want to browse GitHub’s OAuth documentation. Using a library is great, but if you understand the underlying technology you’ll have fewer problems.

Answered By: Chris

I did solve the login redirect URI mismatch by just using http://127.0.0.1:8000/

The problem has to do with the way you’ve configured the urls.py locally. If you have

path('social/', include('social_django.urls', namespace='social')),

then your Authorization callback URL should be

http://localhost/social/complete/github/
Answered By: Tiago Martins Peres