djangooauth-2.0python-requestsmismatchrequest-uri

Got InvalidClientIdError (invalid_request) Mismatching redirect URI. using requests_oauthlib


I am trying to simulate token exchange between consumer and provider (server_to_server) using library requests_oauthlib. I getting error after I receive the code after authorization at provider side and exchanging the code for the token.

So I get my code in my callback function but it is saying that redirect uri doesn't match. I already checked Redirect uri in provider's DB. They are the same. (as variable redirect_uri in code below)

See my Django implementation:

views.py

# create session
from importlib import import_module
SessionStore = import_module(settings.SESSION_ENGINE).SessionStore
session = SessionStore()

client_id = "123456"
client_secret = "123456"
authorization_base_url = 'http://localhost:8000/o/authorize/'
token_url = 'http://localhost:8000/o/token/'

redirect_uri = 'http://localhost:8888/callback'

# ONLY FOR A LOCALHOST
import os
os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'


def index(request):
    provider = OAuth2Session(client_id, redirect_uri=redirect_uri)
    authorization_url, state = provider .authorization_url(authorization_base_url)

    # state is used to prevent CSRF, keep this for later.
    session['oauth_state'] = state
    # redirect to provider    
    return redirect(authorization_url)

def callback(request):
    # handles code from provider and redirects to profile page
    redirect_response = request.build_absolute_uri()
    # (http://localhost:8888/callback?code=123456&state=SomeStateCode)

    state = session.get('oauth_state')
    laas = OAuth2Session(client_id, state=state)

    token = laas.fetch_token(token_url,
                     client_secret=client_secret,
                     authorization_response=redirect_response) # here is mismatch error    
    session['oauth_token'] = token    
    return HttpResponseRedirect(reverse('app:profile'))



def profile(request):
    # shows access token if existing
    if session.get('oauth_token') is not None:
        return HttpResponse("Token: " + session.get('oauth_token'))
    return HttpResponse('No token')

And this is error stacktrace from consumer:

Traceback (most recent call last):
  File "C:\work\envs\consumer\lib\site-packages\django\core\handlers\exception.py", line 35, in inner
    response = get_response(request)
  File "C:\work\envs\consumer\lib\site-packages\django\core\handlers\base.py", line 128, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\work\envs\consumer\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\work\dev\consumer\rbuz\views.py", line 60, in callback
    authorization_response=redirect_response)
  File "C:\work\envs\consumer\lib\site-packages\requests_oauthlib\oauth2_session.py", line 244, in fetch_token
    self._client.parse_request_body_response(r.text, scope=self.scope)
  File "C:\work\envs\consumer\lib\site-packages\oauthlib\oauth2\rfc6749\clients\base.py", line 408, in parse_request_body_response
    self.token = parse_token_response(body, scope=scope)
  File "C:\work\envs\consumer\lib\site-packages\oauthlib\oauth2\rfc6749\parameters.py", line 379, in parse_token_response
    validate_token_parameters(params)
  File "C:\work\envs\consumer\lib\site-packages\oauthlib\oauth2\rfc6749\parameters.py", line 386, in validate_token_parameters
    raise_from_error(params.get('error'), params)
  File "C:\work\envs\consumer\lib\site-packages\oauthlib\oauth2\rfc6749\errors.py", line 415, in raise_from_error
    raise cls(**kwargs)
oauthlib.oauth2.rfc6749.errors.InvalidClientIdError: (invalid_request) Mismatching redirect URI.
[19/Jan/2018 15:57:48] "GET /callback?code=vsWF65mitTtacLQrGDpqsenW3R7Z3k&state=CHsMYmrhzEb12f3KiOkOVz1KEgrzjs HTTP/1.1" 500 90555

Any help with this? Thank you!


Solution

  • I figured it out, you need to pass "redirect_uri " to the OAuth2Session in callback function too. OAuth2Session(client_id, state=state, redirect_uri=redirect_uri**)