1
votes

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.?

1
ensure your AccessToken is, as the comment says, is of the format "Bearer <your assigned token>" - ewong
Verified AccessToken is on type Bearer <Token>. added one more function definition in my problem statement - manju.g.r.

1 Answers

0
votes

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

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

This formats the header in the correct format.