How get bearer token with requests from python - python

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

Related

Python - how to authenticate the server and the api?

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'))

POST build to TeamCity queue

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.

how to save authentication cookie while doing POST login into the server

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)

Get Twitch channel ID from Python

It just says {"error":"Unauthorized","status":401,"message":"error getting authorization token"}, don't know why as I can write on chat with my token.
Here's the code:
url = "https://api.twitch.tv/kraken/channel"
channel_id = urllib.request.Request(url)
channel_id.add_header("Client-ID", CLIENT_ID)
#MY_OAUTH defined as MY_OAUTH = "oauth:123blablabla"
channel_id.add_header("Authorization: OAuth", MY_OAUTH")
response = urllib.request.urlopen(channel_id)
tmpJSON = json.loads(response.read())
EDIT: Here's the Pastebin of get_channel_id function: https://pastebin.com/Jm0EuWk9
It seems that your Authorization header is ill-formed. Supposing that MY_OAUTH as your access token, I believe you meant to write :
channel_id.add_header("Authorization", "OAuth " + MY_OAUTH)
Indeed, the Twitch-API authentication documentation recommends performing the following request when passing the access token in the HTTP header:
curl -H "Authorization: OAuth [access token]" https://api.twitch.tv/kraken/
As you can see, the header needs to be set as Authorization: OAuth [access token], instead of Authorization: OAuth: [access token].

Passing a CSRF token into requests.post()

I saw this post - Passing csrftoken with python Requests
I've been working through it trying to make it work for Greenhouse. I'm trying to build a script that will automate profile creation.
I can fetch data using GET and cookies, but I think I'm I'm getting stuck with X-CSRF. I downloaded the Live HTTP headers plugin for Mozilla to get the CSRF token, but I'm unsure how to pass it in.
So far what I have:
csrf = 'some_csrf_token'
cookie = 'some_cookie_id'
data = dict('person_first_name'='Morgan') ## this is submitting my name on the form
url = 'https://app.greenhouse.io/people/new?hiring_plan_id=24047' ##submission form page
headers = {'Cookie':cookie}
r = requests.post(url, data=data, headers=headers)
Any thoughts how I should construct my requests.post?
If you want requests to handle the cookies for you, you should set a session.
session = requests.session()
logindata = {'authenticity_token': 'whatevertokenis',
'user[email]': 'your#loginemail.com',
'user[password]': 'yourpassword',
'user[remember_me]': '0'}
login = session.post('https://app.greenhouse.io/users/sign_in', data=logindata) #this should log in in, i don't have an account there to test.
data = dict('person_first_name'='Morgan')
url = 'https://app.greenhouse.io/people/new?hiring_plan_id=24047'
r = session.post(url, data=data) #unless you need to set a user agent or referrer address you may not need the header to be added.

Categories

Resources