How to send post to laravel api from python? - python

This is my python request code.
url = "https://test.com/"
r = requests.get(url, verify=False)
xsrf_token = r.cookies.get("XSRF-TOKEN")
headers = {
'X-XSRF-TOKEN':xsrf_token
}
data = {"account": "O_O#gmail.com", "password": "123123"}
r = requests.post(url+'/app/get/users', verify=False, data = data, headers=headers)
In laravel log, I got
[2019-12-27 16:09:14] local.ERROR: The payload is invalid. {"exception":"[object] (Illuminate\Contracts\Encryption\DecryptException(code: 0): The payload is invalid. at /var/www/html/test/vendor/laravel/framework/src/Illuminate/Encryption/Encrypter.php:195)
[stacktrace]
Have any method to solve that? Thanks.

You can't solve the issue with a static xsrf alone since it's doing its job preventing Cross Site Request Forging wich is exactly what you're doing in that piece of code.
To use a route as an API, the laravel installation needs to be configured that way, so, if needed, a stateless way of authentification is used (jwt for example) instead of the session with xsrf token for post methods.
Basicly if it's not configured to be used as an API, you will not be able to use it as an API.

Related

Python API request to internal API with OKTA Authentication

I used to selenium for downloading special reports from webpage where I have to login. Webpage has integrated OKTA Authentication plugin . I find out that there would be better and more effective use internal API requests. So I tried find how to use request python library with creating session, but I am unsuccessful. I tried this code, but it ends with 400 error.
payload = {"password":"password","username":"username","options":{"warnBeforePasswordExpired": True,"multiOptionalFactorEnroll": True}}
with requests.Session() as s:
p = s.post('https://sso.johndeere.com/api/v1/authn', data=payload)
r = s.get("requested_url")
print(p)
I am unable get throw auth. Has anybody experience with breaking OKTA auth plugin using requests library?
Thanks
Best Regards
Merry Christmas and Welcome to Stackoverflow!
Firstly, an HTTP error code of 400 error means one or more settings is wrong at the client side. You can learn more about it here.
You seem to be missing out important headers configuration. You need to set the content-type header correctly otherwise the destination server won't be able to process your data.
Also, as a bonus point. You need to format your payload into a valid JSON string before sending out the request too.
import requests
import json
# Setup proper headers
headers = {
"accept": "application/json, text/plain, */*",
"content-type": "application/json; charset=UTF-8"
}
# Your body data here
payload = {"password":"password","username":"username","options":{"warnBeforePasswordExpired": True,"multiOptionalFactorEnroll": True}}
payload_json = json.dumps(payload) # Format it into a valid JSON str
with requests.Session() as s:
p = s.post('https://sso.johndeere.com/api/v1/authn', headers=headers, data=payload_json)
r = s.get("requested_url")
print(p.content)

Python - Spotify API returning Error 400 "Malformed JSON"

Heyo. I'm trying to make a small application in my spare time that uses the Spotify API . I have managed to get my program to use oAuth 2 to let a user authorize my app to manipulate their Spotify, but I have run into a problem with a certain endpoint on the Spotify API.
The endpoint I am having trouble with is https://api.spotify.com/v1/me/player/play (here's a link to their docs for the endpoint https://developer.spotify.com/console/put-play/). Whenever I try to make a put request to the endpoint I receive a 400 status code with the message "Malformed json" I get this message even when I copy/paste their own json from the docs, so I don't think it's a problem with how I am formatting my json, besides I have used json before to call other endpoints and they haven't had a problem with my formatting on those calls.
Here is my code:
headers = {"Authorization":"Bearer {}".format(access_token)}
url = 'https://api.spotify.com/v1/me/player/play'
payload = {"context_uri": "spotify:album:5ht7ItJgpBH7W6vJ5BqpPr"}
r = requests.put(url, headers=headers, data=payload)
print(r)
print(r.text)
To clarify, access_token is the access token that I have gotten from their authorization process, and I am using python-requests to make the http requests (Here is the docs for that: https://requests.kennethreitz.org/en/master/)
I am wondering if the problem is due to the fact that Spotify uses colons int their track IDs and colons are also used in JSON? I saw in another thread on here that I should try to add "Content-Type":"application/json" to my headers but that didn't change the outcome at all.
Any help is greatly appreciated, and if you need any more info please let me know. Thank you!
If your payload is a dict use json kwargs in requests lib. data works for string payload. Here you go:
r = requests.put(url, headers=headers, json=payload)

slack api calls through python request library

I was making slack api calls through python library slackclient which is a wrapper around slack api. However, for some cases I need to make conventional api calls also with url and get/post method. I was trying to open a direct message channel with another user by my bot. The documentation - https://api.slack.com/methods/im.open says to "Present these parameters as part of an application/x-www-form-urlencoded querystring or POST body. application/json is not currently accepted."
Now in python, I can write,
url = 'https://slack.com/api/im.open'
headers = {'content-type':'x-www-form-urlencoded'}
data = {'token':BOT_TOKEN, 'user':user_id, 'include_locale':'true','return_im':'true'}
r= requests.post(url,headers,data )
print r.text
The message I get is {"ok":false,"error":"not_authed"}
I know the message is "not authed" although I use my bot token and another user id, my hunch is that I'm sending the request in wrong format because I just wrote it some way reading the documentation. I'm not sure how to exactly send these requests.
Any help?
since the Content-Type header is x-www-form-urlencoded sending data in form of dictionary does not work. you can try something like this.
import requests
url = 'https://slack.com/api/im.open'
headers = {'content-type': 'x-www-form-urlencoded'}
data = [
('token', BOT_TOKEN),
('user', user_id),
('include_locale', 'true'),
('return_im', 'true')
]
r = requests.post(url, data, **headers)
print r.text
The second parameter in requests.post is used for data, so in your request you're actually posting the headers dictionary. If you want to use headers you can pass arguments by name.
r= requests.post(url, data, headers=headers)
However this is not necessary in this case because 'x-www-form-urlencoded' is the default when posting form data.

authentication using httplib in python

I am using python 2.7.10. How can I login using httplib connection method.
import httplib
conn = httplib.HTTPConnection("192.18.33.10")
conn.request("POST", "/user/user.form?name=Maharjun&age=23")
res = conn.getresponse()
data = res.read()
What this user.form does is, it will accept some details like name and age from users and server will save them in database. This details can only filled by authenticated users.
I tried some suggestions from python http.requests but those are not working in python-2.7.10.
I know about postman. So, I sent same request in postman using basic authentication method and i converted that into python scripts. In postman we can convert postman-URL into curl/shell/python scripts. So, I converted them into python scripts.
Both are same requests. But I am able to submit the data using postman. But not able to do with python.
postman is giving me a post-man token and basic authentication in headers like below code. is there any mistakes in the code or any suggestions?
import httplib
conn = httplib.HTTPConnection("192.18.33.10")
url = "/user/user.form?name=Maharjun&age=23"
headers = {
'authorization': "Basic some-token",
'cache-control': "no-cache",
'postman-token': "some-token"
}
response = conn.request("POST", url, headers=headers)
print(response.text)
Though it have 'authorization' token I was not able to login by using above code.
can someone help me to write basic authentication using python requests.?

HP QC REST API using python

I tried to connect HP QC using python to create defects and attach files, but I am not able to connect with HP QC. Here is my code:
domain='DEFAULT_773497139'
project='773497139_DEMO'
import requests
url = "https://almalm1250saastrial.saas.hpe.com/qcbin/"
querystring = {"username":"user#gmail.com","password":"password"}
headers = {
'cache-control': "no-cache",
'token': "5d33d0b7-1d04-4989-3349-3005b847ab7f"
}
response = requests.request("POST", url, headers=headers, params=querystring)
#~ print(response.text)
print response.headers
new_header = response.headers
new_url = url+ u'rest/domains/'+domain+u'/projects/'+project
new_querystring = {
"username":"user#gmail.com",
"password":"password",
"domain":'DEFAULT_773497139',
"project":'773497139_DEMO'
}
print new_url
response = requests.request("POST", new_url, headers=new_header, params=new_querystring)
print(response.text)
Now login works fine, but when try other API it asks for, I would get this message:
Authentication failed. Browser based integrations - to login append '?login-form-required=y' to the url you tried to access
If the parameter has been added, then it goes back to login page.
Seems that your urls are not well builded:
base_url ='https://server.saas.hpe.com/qcbin/'
base_url + '/qcbin/rest/domains/
you will get:
..../qcbin/qcbin/...
qcbin twice
The way I do it is to based on python request Sessions. First I create a session, then post my credentials to ../authentication-point/alm-authenticate/ (or sth like this, you should check it) and then using this session I can get, post or do whatever I want.
So:
s = requests.Session()
s.post(`../authentication-point/alm-authenticate/`, data=credentials)
# now session object is authenticated and recognized
# you can s.post, s.get or whatever
I think it's a good url, but I can't check it right now :)
Session issue has beensolved by LWSSO cookie (LWSSO_COOKIE_KEY).
Just send a unicode string to your server and use the header for the basic Authorization as specified by the HP REST API:
login_url = u'https://almalm1250saastrial.saas.hpe.com/qcbin/authentication-point/authenticate'
username,password = user,passwd
logs = base64.b64encode("{0}:{1}".format(username, password))
header['Authorization'] = "Basic {}".format(logs)
POST by using the requests module in python is quite easy:
requests.post(login_url, headers=header)
That's it...now you are authenticated and you can proceed with next action :-) To check on that you can "GET" on:
login_auth = u'https://almalm1250saastrial.saas.hpe.com/qcbin/rest/is-authenticated
you should get a code 200 --> That means you are authenticated.
Hope this help you. Have a nice day and let me know if something is still not clear.
p.s.: to send REST msg in python I am using requests module. It is really easy! You can create a session if you want to send multiple actions--> then work with that sessions--> ALM = requests.session(), then use ALM.post(whatever) and so on :-)

Categories

Resources