1

Am writing a python script to perform OAuth client_credentials type authorization and the fetched bearer token needs to be passed as "Authorization" header parameter in next URL request.

Am able to perform fetching the bearer token as a response i get a string token. now i need to pass this string in the next request header. Below is the code snippet

def getOAuthToken():
    ClientAuth = requests.auth.HTTPBasicAuth(ClientId, ClientSecret)
    PostData = {"grant_type": "client_credentials"}
    TokenResponse = requests.post(TokenUrl, auth=ClientAuth, data=PostData)

    if(TokenResponse.ok):
        print("Token Json response is success")
        print(TokenResponse.content)

    else:
        print("Error in json response")

    TokenJson = TokenResponse.json()
    AccessToken = "Bearer "+TokenJson["access_token"]
    print("AccessToken =",AccessToken)

def GetOAuthJsonResponse(Url, Headers):
    JsonResponse = requests.get(Url, headers=Headers)
    print(JsonResponse.status_code)

    if(JsonResponse.ok):
        print("Token Json response is success")

    else:
        print("Error in json response")

#AccessToken is the Bearer token received from authorization server
#Sample AccessToken will be like "Bearer 123475755959"
Headers = {'Authorization': AccessToken} 
GetOAuthJsonResponse(OAuthBaseUrl, Headers)

Doing so am getting 401 as status_code. 401 signifies Unauthorized access. this seems there is something wrong am doing with adding access token to headers. Any can help me in this.?

2
  • ensure your AccessToken is, as the comment says, is of the format "Bearer <your assigned token>" Commented Aug 2, 2020 at 10:25
  • Verified AccessToken is on type Bearer <Token>. added one more function definition in my problem statement Commented Aug 2, 2020 at 10:33

1 Answer 1

1

Authorization header expects a result like Bearer <accestoken>. Try this line:

Headers = {'Authorization': f"Bearer {AccessToken}"}

This formats the header in the correct format.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for quick response. Added the suggested changes, but still seeing 401 as status code.
Was wrongly hard coding the access token to a static value. minor modifications along with the above suggested header format is working fine. Now am getting success response from authenticated rest api.
Glad I could help:)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.