Trouble getting access token when using github OAuth2

1.1k Views Asked by At

I am trying to follow Users are redirected back to your site by GitHub step

I was able to get an authorization code, but I am having trouble exchanging that for an access token.

This is the call with the auth code

http://localhost:8080/login/oauth2/code/github?
code=1e16b9f5e7e1b63ce1d4
&state=nS7zT9elsOzMmf6SKUXJz6m_Z-PBvhfUfObZiR3UhWI%3D

I am trying exchange that authcode for an access token. I tried with and without grant_type in the parameters. Is there anything obviously wrong in the curl command below?

curl --location --request POST 'https://github.com/login/oauth/access_token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--header 'Cookie: user_session=omYLX_QFvwdlluotRIJVi_mz7v_FQaIdQBZtkELBlBWBkhnj; __Host-user_session_same_site=omYLX_QFvwdlluotRIJVi_mz7v_FQaIdQBZtkELBlBWBkhnj' \
--data-urlencode 'client_id=xxxxx' \
--data-urlencode 'client_secret=xxxxx' \
--data-urlencode 'code=1e16b9f5e7e1b63ce1d4' \
--data-urlencode 'redirect_uri=http://localhost:8080/login/oauth2/code/github' \
--data-urlencode 'state=nS7zT9elsOzMmf6SKUXJz6m_Z-PBvhfUfObZiR3UhWI%3D' \
--data-urlencode 'grant_type=authorization_code'

This is the error message I get.

error=bad_verification_code&error_description=The+code+passed+is+incorrect+or+expired.&error_uri=https%3A%2F%2Fdocs.github.com%2Fapps%2Fmanaging-oauth-apps%2Ftroubleshooting-oauth-app-access-token-request-errors%2F%23bad-verification-code
1

There are 1 best solutions below

0
On

I think you are sending unnecessary parameters with your request. whereas the parameters to exchange the authcode with OAuth token are as below

  • app credentials ( client_id + client_secret)

  • code

I don't have a curl example for now but here is the example from my python script where I do the same thing e.g. exchange authcode with OAuth Token

 data = {
            'client_id': settings.CLIENT_ID,
            'client_secret': settings.CLIENT_SECRET,
            'code': self.code,
        }
 headers = {'Accept': 'application/json'}
 response = requests.post(
       'https://github.com/login/oauth/access_token',
       data=data,
       headers=headers)

Hope it helps