I am trying to make a http request using Python3.8.5 + requests 2.25.0. The request contains Authorization Token in the header.
When use Postman to make the request, I can get response without issue. But, when I use following python code to make the request, it returns 401. Not sure what is worng in the code.
401 {"detail":"Authentication credentials were not provided."}
Following are the python code having issues.
import requests
url = <MY_URL>
payload={}
headers = {
'Authorization': 'TOKEN <MY_TOKEN>'
}
response = requests.request("GET", url, headers=headers, data=payload)
print(response.text)
The problem resloved by adding a / at the end of the request url. :-)
Related
I have the following Python function which takes an access_token from my company's access token provider and hits the URL stored in matter_hydration_url:
def hydration_request(access_token, matter_hydration_url):
hydration_call_headers = {'Authorization': 'Bearer ' + access_token}
response = requests.post(matter_hydration_url, headers=hydration_call_headers)
response.raise_for_status()
I have tested BOTH access_token AND matter_hydration_url externally, through POSTMAN, and they both work. Unfortunately, in this code, the response variable has status_code field 401. I think I am mis-using requests.post(). Any ideas?
Worked after I changed Bearer in the String of line 2 to Access
¯_(ツ)_/¯
I am trying to make a GET request to an endpoint which uses AWS Authorization. I made request using postman, It works. But when i tried following method in python, it's giving error.
CODE
url = 'XXX'
payload = {}
amc_api_servicename = 'sts'
t = datetime.utcnow()
headers = {
'X-Amz-Date': t.strftime('%Y%m%dT%H%M%SZ'),
'Authorization': 'AWS4-HMAC-SHA256 Credential={}/{}/{}/{}/aws4_request,SignedHeaders=host;x-amz-date,Signature=3ab1067335503c5b1792b811eeb84998f3902e5fde925ec8678e0ff99373d08b'.format(amc_api_accesskey, current_date, amc_api_region, amc_api_servicename )
}
print(url, headers)
response = requests.request("GET", url, headers=headers, data=payload)
ERROR
The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method.
Please point me in the right direction.
import boto3
client = boto3.client('sts')
respone=client.assume_role(RoleArn='your i am urn',RoleSessionName='PostmanNNN')
I am working with the CF API RESTful services. Trying to get an access token from cloud foundry's UAA API using https://login..../oauth/token web method.
I have verified that headers & body content is correct, but calling the api always returns a 400 error code with message missing grant type.
I have implemented this call in Objective-C, Swift & now Python. All tests return the same result. Here is my code example in Python:
import json
import requests
import urllib
params = {"grant_type": "password",
"passcode": "xxx"
}
url = "https://login.system.aws-usw02-pr.ice.predix.io/oauth/token"
headers = {"Authorization": "Basic Y2Y6", "Content-Type": "application/json", "Accept": "application/x-www-form-urlencoded"}
encodeParams = urllib.parse.urlencode(params)
response = requests.post(url, headers=headers, data=encodeParams)
rjson = response.json()
print(rjson)
Each time I run this, I get the response
error invalid request, Missing grant type
Any help would be greatly appreciated.
Your code mostly worked for me, although I used a different UAA server.
I had to make only one change. You had the Accept and Content-Type headers flipped around. Accept should be application/json because that's the format you want back, and Content-Type should be application/x-www-form-urlencoded because that's the format you are sending.
See the API Docs for reference.
import json
import requests
import urllib
import getpass
UAA_SERVER = "https://login.run.pivotal.io"
print("go to {}/passcode".format(UAA_SERVER))
params = {
"grant_type": "password",
"passcode": getpass.getpass(),
}
url = "https://login.run.pivotal.io/oauth/token"
headers = {
"Authorization": "Basic Y2Y6",
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "application/json"
}
encodeParams = urllib.parse.urlencode(params)
response = requests.post(url, headers=headers, data=encodeParams)
rjson = response.json()
print(json.dumps(rjson, indent=4, sort_keys=True))
I made a couple other minor changes, but they should affect the functionality.
Use getpass.getpass() to load the passcode.
Set the target server as a variable.
Pretty print the JSON response.
The only other thing to note, is that the OAuth2 client you use must be allowed to use the password grant type. It looks like you're using the same client that the cf cli uses, so if your UAA server is part of a standard Cloud Foundry install that is likely to be true, but if it still doesn't work for you then you may need to talk with an administrator and make sure the client is set up to allow this.
I'm trying to generate an access token from an API using the following required information:
Authorization endpoint: https://api.paylocity.com/IdentityServer/connect/token
Authorization Header
The request is expected to be in the form of a basic authentication request, with the "Authorization" header containing the client-id and client-secret. This means the standard base-64 encoded user:password, prefixed with "Basic" as the value for the Authorization header, where user is the client-id and password is the client-secret.
Content-Type Header
The "Content-Type" header is required to be "application/x-www-form-urlencoded".
Other Values
The request must post the following form encoded values within the request body:
grant_type = client_credentials
scope = WebLinkAPI
I've tried using the Python 'requests' package without success, see below:
import requests
url = "https://api.paylocity.com/IdentityServer/connect/token"
headers = {
'Authorization': "Basic **********:**********",
'Content-Type': "application/x-www-form/urlencoded"
}
body = {
'grant_type': "client_credentials",
'scope': 'WebLinkAPI'
}
response = requests.request("POST", url, headers=headers, params=body)
print(response.text)
Instead of an access token, I receive an error message:
{"error":"invalid_client"}
I've verified that my base64 encoded username and password are correct, it looks something like "G/RaNdOm:MoReRaNdOm==" and when I add them to postman it works so my credentials are correct. What could be wrong?
I resolved this. There were two issues, the Authorization header was not using ASCII as the destination charset with base64 encoding. The other issue was trying to add the additional values to the parameters instead of the body in the requests package. The solution was to replace "params" with "data". Here was the solution:
url = "https://api.paylocity.com/IdentityServer/connect/token"
body = "grant_type=client_credentials&scope=WebLinkAPI"
headers = {
'Content-Type': "application/x-www-form-urlencoded",
'Authorization': "Basic ***(base64ASCII)username:password***",
}
response = requests.request("POST", url, data=body, headers=headers)
print(response.text)
I'm trying to make a post request with python's requests module.
I'm passing the headers, cookies, and data as part of the post request.
When I make the request,I get 400 bad request in the output.
I verified the payload and it looks correct to me. I'm wondering If my syntax for cookie is correct.
#!/usr/local/bin/python
import requests
session = "ASDFGHTR/=FGHYTYKSDMN="
lastmanaged = "9ycG9yYXRpb25fRGlyZWN0I"
header = {'akm-accept':'akm/cookie'}
cookie = {'SESSION': session,
'LASTMANAGED':lastmanaged}
data = {'client': '0ad3cfb66-4fa0-b94a-1bf712eae628&grant_type=password_assertion'}
url = "https://hostname-goes-here"
session = requests.Session()
response = session.post(url, headers=header, cookies=cookie, data=data,
verify=False, allow_redirects=False)
print(response.text)
print(response.status_code)
output:
{"code":"invalid_request","title":"One or more fields in request are invalid","incidentId":"f1fbba64-17e4-4d88-852f-01c137fa012e","requestId":"-5011561246754340090","solution":"none"}
400