I am trying to use the TeamCity REST API to add a build to the queue but am running into some difficulty with authorization.
I have the url to our teamcity server defined, and have generated an authorization token through the admin page
TEAMCITY_URL = 'http://teamcity.somedomain.com'
BEARER_TOKEN = 'SOMELONGTOKEN'
With this URL and token I can successfully make GET requests
import json
import requests
session = requests.Session()
session.headers.update({
'Accept': 'application/json',
'Authorization': f'Bearer {BEARER_TOKEN}',
})
response = session.get(f'{TEAMCITY_URL}/app/rest/projects/example/buildTypes')
assert(response.status_code == requests.codes.ok) # this succeeds, can parse response fine later
but then if I try to POST a build to the queue I get a 403
payload = {
'branchName': 'master',
'buildType': {
'id': buildID # assume this was already defined
}
}
response = session.post(f'{TEAMCITY_URL}/app/rest/buildQueue', json=payload)
assert(response.status_code == requests.codes.ok) # fails with 403
the latter response.text is
'403 Forbidden: Responding with 403 status code due to failed CSRF check: authenticated POST request is made, but neither tc-csrf-token parameter nor X-TC-CSRF-Token header are provided.. For a temporary workaround, you can set internal property teamcity.csrf.paranoid=false and provide valid Origin={teamcity_url} header with your request\n'
How can I correctly use this bearer token to perform a POST request?
The fix for this was I needed to first make a GET request for a CSRF token. I could then use this token to update the session headers with a 'X-TC-CSRF-Token' as follows
response = session.get(f'{TEAMCITY_URL}/authenticationTest.html?csrf')
assert(response.status_code == requests.codes.ok)
csrf_token = response.text
session.headers.update({
'X-TC-CSRF-Token': csrf_token
})
then the subsequent POST would succeed. More details in official docs.
Related
I'm trying to replicate a login to a page with python and the requests module but I need a token bearer.
This site doesn't require a login password connection but just an event code (wooclap.com)
I cannot find when the token is recovered by looking at header and json responses.
If you can help me
Thanks
once you put in a event code check the network tab on you're chrome console there should be a request wich returns the token. either in the reponse header or the json,
I'd recommend finding it using DevTools in your browser (F12).
In network you can see the login request mainly under headers and response. I've used this to implemented it below in python for you.
import requests
# Set the URL of the login page
url = "https://app.wooclap.com/api/auth/local/login"
# Set the login credentials
data = {"username": "< !!enter username here!! >", "password": "< !!enter password here!! >"}
# Send the login request and store the response
response = requests.post(url, data=data)
# Get the JSON response body
json_response = response.json()
# Get the AWT token from the JSON response
awt_token = json_response.get("token")
# Set the URL of the resource you want to access
url = "https://app.wooclap.com/public/events"
# Set the authorization header of your request, using the Bearer scheme
headers = {"Authorization": f"Bearer {awt_token}"}
# Send the request and store the response
response = requests.get(url, headers=headers)
print(response.text)
To send a GET request with a Bearer Token authorization header using Python, you need to make an HTTP GET request and provide your Bearer Token with the Authorization: Bearer {token} HTTP header
When I try to link the Wix API, I get this error:
The redirect url doesn’t match the one defined in your app configuration. Double check that it starts with https.
I looked at the code and it already has https:
import requests
def handler(pd: "pipedream"):
token = f'{pd.inputs["wix"]["$auth"]["oauth_access_token"]}'
authorization = f'Bearer {token}'
headers = {"Authorization": authorization, "Content-Type": 'application/json'}
r = requests.get('https://www.wixapis.com/contacts/v4/contacts', headers=headers)
# Export the data for use in future steps
return r.json()
What should I do here?
api linking not working
I am trying to send an API request to a server that needs http authentication.
The (Wordpress server) is set to authenticate the API using basic authentication.
First I am setting the session using the code
with requests.sessions.Session() as session:
session.auth = ('my_user', 'my_password')
session.get(url)
I get 200 as expected.
Then I send the API request
credentials = "user:password"
token = base64.b64encode(credentials.encode())
header = {"Authorization": "Basic " + token.decode('utf-8')}
response = requests.get(url=url, headers=header)
But I get error 401 in the response.
How can I do it differently to make it work?
i have some sample of mine, i hope it'll help you:
header = {....}
data = {...}
response= requests.post(url=url, data=data,headers=header,auth=(user,password))
as far as I know, wordpress does not even accept Authentication user/password by default.
you can only login through cookies (source)
but there is a way to authenticate rest api using user/password and that is plugins. I suggest Wordpress REST API Authentication
then usage would be so easy like :
import requests
headers = {
'Authorization': 'Basic base64encoded <username:password>',
'Content-Type': 'application/x-www-form-urlencoded',
}
data = 'title=sample post&status=publish'
response = requests.post('http://example.com/wp-json/wp/v2/posts', headers=headers, data=data)
Taking from the two answers (thanks!), here is the answer that is a merge of the two.
The API authentication is sent in the header (and an API authentication plugin is needed in WP).
credentials = "user:password"
token = base64.b64encode(credentials.encode())
header = {"Authorization": "Basic " + token.decode('utf-8')}
The session authentication is sent in the auth parameter of the request
response = requests.get(url=url, headers=header, auth=('my_user', 'my_password'))
I'm currently using the Python Requests module to add videos to a playlist created by me. On the docs for playlistItems.insert, it says authorization is required with one of three possible scopes. I have created an OAUTH2.0 credential token in my project's credential panel and set the scope correctly. Currently I'm trying to pass the credential as follows:
payload = {
'access_token': [My Client ID],
'part': 'snippet'}
new_vid = requests.post(f'{base_url}playlistItems', params=payload)
When executing the code, I get the following error message:
"message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project."
Am I passing the authorization token in the correct place, or should I be passing it somewhere else in the POST request?
You can pass the Authorization token as a header parameter. Check the example below:
import requests
headers = {
'Authorization': 'Bearer [YOUR_ACCESS_TOKEN]',
'Accept': 'application/json',
'Content-Type': 'application/json',
}
params = (
('key', '[YOUR_API_KEY]'),
('part','snippet')
)
response = requests.post('https://youtube.googleapis.com/youtube/v3/playlistItems', headers=headers, params=params)
I am trying to login into the server via post with my python script, but it is not working although when i am doing the same POST via postman it is working fine. I believe my python script is not saving the authentication cookie information or may be i have to add some more fields in my payload. I am at very very beginner level of programming so please guide me how i can save that authentication cookie which i can further use in my next GET, POST requests.
When i run this POST request via postman. I simply give username and password in the body and i got the following successful response
{
"ErrorCode": 0,
"Data": {
"role": "admin",
"_id": "7c9e7mdf4d249212282480zb",
"name": "test5"
}
}
but when I run below mentioned Python script, I am getting
<!DOCTYPE HTML PUBLIC"-//IETF//DTD HTML 2.0//EN">
500 Internal Server error
Please find below mentioned my python script
import requests
url = "http://172.125.169.21/api/user/login"
payload = "{\"name\": \"test5\", \"password\": \"Hello123\"}"
response = requests.request("POST", url, data=payload)
print(response.text)
print(response.headers)
For the requests library in python, the data object takes a python dict object, not a JSON string. If you were to edit your code to:
import requests
import json
url = "http://172.125.169.21/api/user/login"
payload = {"name": "test5", "password": "Hello123"}
headers = {'Content-Type': "application/json"}
response = requests.request("POST", url, json=payload, headers=headers)
# the json parameter should handle encoding for you
print(response.text)
print(response.headers)
Cookies are available to you in the cookies parameter of the response object. See the requests documentation for more information.
print(json.dumps(response.cookies, separators=(",",":"), indent = 4))
This should pretty print the cookie(s) you've received. You can use requests' session handling abilities or a variable to store this information, however you choose. We'll save these cookies to a requests cookiejar:
cookies = response.cookies
and we'll use those cookies in the authorization check or any other requests:
auth_check_url = "172.125.169.21/api/user/checkLogin"
response = requests.get(auth_check_url, cookies=cookies)
print(response.text)