Python Script to post Authorization Header to specific IP/port - python

I need a python script that posts a given Authorization Bearer header to a specific ipand port.
This is what I have so far.
#!/usr/bin/python
import urllib3
import certifi
http = urllib3.PoolManager(ca_certs=certifi.where())
url = 'http://172.10.10.2:3000'
req = http.request('POST', url, fields={'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjbWQiOiJscyR7SUZTfS1sYSR7SUZTfS90bXAvbmMifQ.EziCTtJn1PpPXvemJllF36w7ADNkhKiktZ5sv9ADR3o'})
print(req.data.decode('utf-8'))
I currently get an error when running this stating that the Required authorization token is not found
The bearer code is created manually and then input into the script, if there was a way to import that from the site I create it on that would be helpful.
What I need the output to be in this -
GET / HTTP/1.1
Host: 172.10.10.2:3000
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: close
Upgrade-Insecure-Requests: 1
Cache-Control: max-age=0
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjbWQiOiJpcCR7SUZTfWEifQ.RkoZinBcg2_5HRGgv1AtErhscIVBRv2hUcGIF08ZlCM

Related

Where to get header values for request while webscraping?

I am trying to web scrap "https://pricehistoryapp.com/" to obtain the product's highest and lowest prices. I am using python requests library for this.
I have observed that this site obtains the next address to go by using a request named 'getSlugFromUrl' made to server. This is also first xhr request made as search button is pressed. I understood some part of pay load and headers but not able to figure out others:
Header:
:authority: ph.pricetoolkit.com
:method: POST
:path: /api/product/history/getSlugFromUrl
:scheme: https
accept: application/json
accept-encoding: gzip, deflate, br
accept-language: en-US,en;q=0.9
auth: 8nV5lXoVu/Qk2z5BhZmbPj4rxSdd35ThEbiRgK1kCCz+wU0Guh+6qal03DS3J6HG
cache-control: no-cache
content-length: 738
content-type: application/x-www-form-urlencoded
origin: https://pricehistoryapp.com
pragma: no-cache
referer: https://pricehistoryapp.com/
sec-ch-ua: "Microsoft Edge";v="107", "Chromium";v="107", "Not=A?Brand";v="24"
sec-ch-ua-mobile: ?1
sec-ch-ua-platform: "Android"
sec-fetch-dest: empty
sec-fetch-mode: cors
sec-fetch-site: cross-site
user-agent: Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Mobile Safari/537.36 Edg/107.0.1418.24
Payload:
purl:https://www.flipkart.com/viewsonic-vx-series-24-inch-wqhd-led-backlit-ips-panel-frameless-monitor-vx2480-2k-shd/p/itmedaf0773f47ba?pid=MONG5KEK2GDSGTSY
lid: LSTMONG5KEK2GDSGTSYAQGKIT
marketplace: FLIPKART
store: 6bo/g0i/9no
srno: b_1_5
otracker: hp_omu_Best+of+Electronics_4_3.dealCard.OMU_NOBMPKW1HQ7A_3
iid: 083d5b0d-6840-426e-811b-28b45d6e6ea7.MONG5KEK2GDSGTSY.SEARCH
ssid: d5n99toygg0000001667914476777
For instance from where is auth obtained from in header, or from where lid, iid, ssid obtained for payload. I know the question is really stupid, but please guide me towards a solution. Thanks in advance.

How to call Laravel API from Python correctly

I am using Laravel 8 and Sanctum and attempting to make an API call from Python into the Laravel app.
I don't seem to be sending the request variables correctly from python as they are not being picked up as $request->variable (see "auction_item_id":null in Laravel log below) however they do show up in the request (see below Laravel log).
Is this a problem with the python request header?
Python:
import requests
import re
import json
############## LOGIN ####################
url = 'http://127.0.0.1:8082/api/apilogin'
data = {
'email': 'user#email.com',
'password': 'password'}
r = requests.post(url, data=data)
user = json.loads(r.text)
############## MAKE REST API CALL using login token from prior call ####################
url2 = 'http://127.0.0.1:8082/api/beginlivebiddingforitemAPI'
token = "Bearer " + user["token"]
headers = {"Authorization": token, 'Accept': 'application/json'}
data = {
'auction_id' : 103,
'auction_item_id' : 1224
}
rr = requests.get(url2, data=data, headers=headers)
AuctionBidsController:
public function beginlivebiddingforitem (Request $request){
Log::info("AuctionBidsController#beginlivebiddingforitem", ['auction_item_id' => $request->auction_item_id]);
Api.php:
Route::post('/apilogin', 'UsersController#APIlogin');
Route::middleware(['auth:sanctum'])->group(function () {
Route::get('/beginlivebiddingforitemAPI', 'AuctionBidsController#beginlivebiddingforitem');
});
Laravel log:
[2020-11-06 16:46:44] local.INFO: AuctionBidsController#beginlivebiddingforitem {"auction_item_id":null,"request":{"Illuminate\\Http\\Request":"GET /api/beginlivebiddingforitemAPI HTTP/1.1
Accept: application/json
Accept-Encoding: gzip, deflate
Authorization: Bearer 100|3EjawNPRinapHXxZvDirzyKM73AzeuJC8OTP6xOZ
Connection: keep-alive
Content-Length: 35
Content-Type: application/x-www-form-urlencoded
Host: 127.0.0.1:8082
User-Agent: python-requests/2.23.0
auction_id=103&auction_item_id=1224"}}
^^^^^^^^^^^^^^^
THEY ARE HERE
** But look at "auction_item_id":null **
Here is what a normal request looks like inside laravel:
[2020-11-06 18:34:56] local.INFO: AuctionBidsController#beginlivebiddingforitem {"auction_item_id":"1223","request":{"Illuminate\\Http\\Request":"GET /beginlivebiddingforitem?auction_id=103&auction_item_id=1223 HTTP/1.1
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Connection: keep-alive
Cookie: laravel_cookie_consent=1; _ga=GA1.1.1339345323.1594720189; PGADMIN_INT_KEY=129e52c8-dddd-41a0-bc43-53e91dec5402; pga4_session=1c3a240a-46a1-4a9e-8e25-d489bb8ddddddddNltIXmby1M+34KepOYCsGAsY=; PGADMIN_LANGUAGE=en; _gid=GA1.1.1579327561.1604514920; _gat_gtag_UA_170463940_1=1; XSRF-TOKEN=eyJpdiI6ImIxT00yWW54REE2emVQSEpZZzZRRmc9PSIsInZhbHVlIjoiWmlCZGhia1pxeVJ0TmU4NGRBV2xMUURsS21RT0cyWGZUYddddddddddddddddddddddU9oUHg3cGQrdWZhd2gybnRCZ0xUajcwdEhuREh5OE5FcWkzV2tWb3lKOTRwUlljWld4TE9KL3BiMFp0M1dzeklmY2VhaEUiLCJtYWMiOiI0OWZhYmE3ZWM0ZjFhNTU5OWM1ZWE1MmY0MmIyMWQ3YTU1YzE3MmI0NWM1YjY0NTE0MzdhYTVmOWNmODIzMWVlIn0%3D; icollect_session=eyJpdiI6Ik5xSlAzR3NaZUR4QUhxV0RBRFBvd2c9PSIsInZhbHVlIjoianJLbFdVUDJCL2FKZEo5NTFUMElVUFJMRm9BdddddddddddddddHdYL3Arc3Avc1JTcUE5RmNPZ1J2MUVxblFUbmREcHJJeUZJaHZNVzJHTVNhR2p6Snp6M2JkQXJObE9BQU91Si9RbVIzRXMiLCJtYWMiOiI5MzcwMjc5ZWQ0MDE5ZDk2NTVmYmJjNGQ5NWYzMGY2YTVkMDI5YWQ0YTlkNGU1YTUyZTIyYzhkODU4NjNiNDA2In0%3D
Dnt: 1
Host: 127.0.0.1:8082
Referer: http://127.0.0.1:8082/bidliveauctioneer/103
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-origin
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.80 Safari/537.36 Edg/86.0.622.43
X-Csrf-Token: wrdZoCDCVeqddddzVxAxByw183bFMuddddP4QBKy
X-Requested-With: XMLHttpRequest
X-Socket-Id: 9357.547174
Cookie: laravel_cookie_consent=1; _ga=; PGADMIN_INT_KEY=; pga4_session=; PGADMIN_LANGUAGE=; _gid=; _gat_gtag_UA_170463940_1=; XSRF-TOKEN=wrdZoCDCVeqddddzVxAxByw183bFMuddddP4QBKy; icollect_session=Qx2QddddNvlIg3ogQ596BdddducrFk4Bmi0nLA89
**note that variables occur right after the GET
GET /beginlivebiddingforitem?auction_id=103&auction_item_id=1223 **
I was using data = data and it's params = data on requests.get(url2, params=data, headers=headers).
Source: https://requests.readthedocs.io/en/master/user/quickstart

Using Python and requests module to post

There are similar questions posted, but I still seem to have a problem. I am expecting to receive a registration email after running this. I receive nothing. Two questions. What is wrong? How would I even know if the data was successfully submitted as opposed to the page just loading normally?
serviceurl = 'https://signup.com/'
payload = {'register-fname': 'Peter', 'register-lname': "Parker", 'register-email': 'xyz#email.com', 'register-password': '9dlD313kF'}
r2 = requests.post(serviceurl, data=payload)
print(r2.status_code)
The url for the POST request is actually https://signup.com/api/users, and it returns 200 (in my browser).
You need to replicate what your browser does. This might include certain request headers.
You will want to use your browser's dev tools/network inspector to gather this information.
The information below it from my Firefox on my computer:
Request headers:
Host: signup.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:73.0) Gecko/20100101 Firefox/73.0
Accept: application/json, text/plain, */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Content-Type: application/json;charset=utf-8
Content-Length: 107
Origin: https://signup.com
Connection: keep-alive
Referer: https://signup.com/
Cookie: _vspot_session_id=ce1937cf52382239112bd4b98e0f1bce; G_ENABLED_IDPS=google; _ga=GA1.2.712393353.1584425227; _gid=GA1.2.1095477818.1584425227; __utma=160565439.712393353.1584425227.1584425227.1584425227.1; __utmb=160565439.2.10.1584425227; __utmc=160565439; __utmz=160565439.1584425227.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); __utmt=1; __qca=P0-1580853344-1584425227133; _gat=1
Pragma: no-cache
Cache-Control: no-cache
Payload:
{"status":true,"code":null,"email":"TestEmail#hotmail.com","user":{"id":20540206,"email":"TestEmail#hotmail.com","name":"TestName TestSurname","hashedpassword":"4ffdbb1c33d14ed2bd02164755c43b4ad8098be2","salt":"700264767700800.7531319164902858","accesskey":"68dd25c3ae0290be69c0b59877636a5bc5190078","isregistered":true,"activationkey":"f1a6732b237379a8a1e6c5d14e58cf4958bf2cea","isactivated":false,"chgpwd":false,"timezone":"","phonenumber":"","zipcode":"","gender":"N","age":-1,"isdeferred":false,"wasdeferred":false,"deferreddate":null,"registerdate":"2020/03/17 06:09:27 +0000","activationdate":null,"addeddate":"2020/03/17 06:09:27 +0000","admin":false,"democount":0,"demodate":null,"invitationsrequest":null,"isvalid":true,"timesinvalidated":0,"invaliddate":null,"subscribe":0,"premium":false,"contributiondate":null,"contributionamount":0,"premiumenddate":null,"promo":"","register_token":"","premiumstartdate":null,"premiumsubscrlength":0,"initial_reg_type":"","retailmenot":null,"sees":null,"created_at":"2020/03/17 06:09:27 +0000","updated_at":"2020/03/17 06:09:27 +0000","first_name":"TestName","last_name":"TestSurname"},"first_name":"TestName","last_name":"TestSurname","mobile_redirect":false}
There's a lot to replicate. Things like the hashed password, salt, dates, etc would have been generated by JavaScript executed by your browser.
Keep in mind, the website owner might not appreciate a bot creating user accounts.

How to log HTTP message body of incoming POST - Flask

I'm setting up google pub/sub on a Flask server and have successfully set the endpoint to POST to https://myapp.ngrok.io/pubsub/push/ according to the documentation.
In my console it returns this request with a 400 error:
66.102.8.237 - - [24/Oct/2019:04:30:35 +0000] "POST /pubsub/push/ HTTP/1.1" 400 148 "-" "APIs-Google; (+https://developers.google.com/webmasters/APIs-Google.html)"
I'm trying to access the message body to troubleshoot the 400 error but haven't been able to print the message body using print(request.get_json()).
Is there a way I can access the HTTP message body in Flask or is the above error the only information sent to my app?
The HTTP header data for the request is stored inside the header attribute requests. So for example, if you do,
print(request.header)
you'd get something like this on the console:
Host: localhost:5000
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:70.0) Gecko/20100101 Firefox/70.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Cookie: csrftoken=CQmXNt256FqZev0S2fRtw04ZSTlUnvYHGRbNn6NH5OVn36W7qPMZw0s9N3anGHMG
Upgrade-Insecure-Requests: 1
Cache-Control: max-age=0

Send post request with cookies [python]

POST /search HTTP/1.1
Host: chatango.com
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:51.0) Gecko/20100101 Firefox/51.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Cookie: cookies_enabled.chatango.com=yes; fph.chatango.com=http; id.chatango.com=programmable; auth.chatango.com={MY AUTH KEY - I already have this}
Connection: keep-alive
Referer: http://st.chatango.com/flash/sellers_external.swf
Content-Type: application/x-www-form-urlencoded
Content-Length: 27
s=B&ama=99&ami=13&t=25&f=20
I'd really like to know how to send this via python, I haven't found anything except sending that data part, I really don't understand how I'm supposed to send the cookie data as I have it stored into a variable which I got through an API, which obtains it through sockets.
You can add new headers in the request() method:
HTTPConnection.request(method, url[, body[, headers]])
See request documentation.
To add a cookie, just add the Cookie header.
Here is a POST example from the Python site:
import httplib, urllib
params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
headers = {"Content-type": "application/x-www-form-urlencoded",
"Accept": "text/plain"}
conn = httplib.HTTPConnection("musi-cal.mojam.com:80")
conn.request("POST", "/cgi-bin/query", params, headers)
response = conn.getresponse()
print response.status, response.reason
data = response.read()
conn.close()

Categories