requests-oauthlib icon indicating copy to clipboard operation
requests-oauthlib copied to clipboard

State not equal in request and response

Open mooyg opened this issue 2 years ago • 2 comments

Getting an error oauthlib.oauth2.rfc6749.errors.MismatchingStateError: (mismatching_state) CSRF Warning! State not equal in request and response

@router.get("/github", response_class=RedirectResponse)
async def github():
    authorization_url, state = github_oauth.authorization_url(authorization_base_url)
    return authorization_url


@router.get("/callback")
async def authorize(code: str):
    github_oauth.fetch_token(
        token_url, client_secret=client_secret, authorization_response=code
    )
    r = github_oauth.get("https://api.github.com/user")
but when I log state inside `github` function it logs same as in the query param `state` of the callback url

mooyg avatar Oct 13 '21 11:10 mooyg

Hi, Can you tell us how are you creating github_oauth and when? We can't see how are you using the state variable in this example ? Thanks

JonathanHuot avatar Nov 06 '21 22:11 JonathanHuot

I experienced a similar issue re: not being able to exchange tokens due to the state parameter. Turns out it's because the OAuthSession keeps track of the state it generated earlier and then there is validation against the authorization_response if that parameter is used.

You can by-pass the state validation by passing in the code parameter versus the authorization_response parameter, i.e.

oauth_client.fetch_token(token_url, client_secret=client_secret, code=code)

alysivji avatar Feb 21 '23 19:02 alysivji