Pass Additional header to twilio - python

When I access any api under example.com/v3/ , I need to pass headers like ** token, clientip **, etc. and its mandatory headers.
Now when I make request to example.com/v3/notify , headers like token, clients are passed. This url is redirected internally to -> example.com/twilio.
I am stuck at forwarding these headers internally to the example.com/twilio
What shall I do to forwarded these headers as well?
Sample Code in Python which makes call to twiml_url(example.com/twilio):
client.calls.create(
to=call_number,
from_=TWILIO_FROM_NUMBER,
url=twiml_url,
method="GET",
fallback_method="GET",
status_callback_method="GET",
record="false"
)

Twilio developer evangelist here.
You can't get Twilio to send extra headers on your behalf. Twilio implements it's own header validation so that you can validate requests came from Twilio itself.
I would recommend implementing those checks and turning off your own header validation for requests made to the URL you use for Twilio.

Related

Netsuite: OAuth1 / Token-Based Authentication where to put the state parameter

I want to connect to Netsuite via Token-Based Authentication (i.e. OAuth1) as documented here.
In the section Step One Obtain An Unauthorized Request Token it is written that an optional state parameter can be added to the Authorization Header. There they also refer to RFC 6749, Section 4.1.1 for further information. However, what is explained there has nothing to do with OAuth1.0 but Oauth2.0.
The reason why I depend on the state parameter is that I have the url to which the callback server shall forward the request after the authorization is done encoded in it (using JWT).
Now when I create the OAuth1 authorization header with oauthlib using the sign method from oauthlib.oauth1.Client in Python
from oauthlib.oauth1 import SIGNATURE_HMAC_SHA256
from oauthlib.oauth1 import Client
client = Client(client_key=CONSUMER_KEY,
client_secret=CONSUMER_SECRET,
callback_uri=CALLBACK_URL,
signature_method=SIGNATURE_HMAC_SHA256)
uri, headers, body = client.sign(uri="https://123456.restlets.api.netsuite.com/rest/requesttoken", http_method='POST')
I get this for headers:
headers = {
'Authorization': 'OAuth oauth_nonce="123..", oauth_timestamp="163...", oauth_version="1.0", oauth_signature_method="HMAC-SHA256", oauth_consumer_key="f18...", oauth_callback="...", oauth_signature="9kae..."'
}
I can acquire the temporary credentials when sending the request with this headers to https://123456.restlets.api.netsuite.com/rest/requesttoken.
Still as I need the state parameter later on on my side I somehow need to add the state parameter to the authorization header (at least that is what Netsuite says in their documentation).
When I add my state parameter to the authorization header (the one created before by the sign method from oauthlib.oauth1.Client) like this
from oauthlib.common import to_unicode
headers["Authorization"] = f'{headers["Authorization"]}, state="{to_unicode(data=state, encoding="UTF-8")}"'
which results in this for headers (I will refer to it as new_headers):
# headers with state appended to Authorization
headers = {'Authorization': 'OAuth oauth_nonce="123...", oauth_timestamp="163...", oauth_version="1.0", oauth_signature_method="HMAC-SHA256", oauth_consumer_key="f18...", oauth_callback="...", oauth_signature="9kae...", state="eyJ0..."'}
I get this response when trying to send a request to the request token url with this header:
{"error" : {"code" : "USER_ERROR", "message" : "Invalid login attempt."}}
When I do it differently (not as specified in the doc) and add the state parameter to the request token url like this "https://123456.restlets.api.netsuite.com/rest/requesttoken?state=eyJ0..." and send the previous header with authorization not including the state (i.e. headers) I again get to the login page. So I can assume this could work.
My problem is that I cannot test it at the moment with a Netsuite account so I just need to implement it according to the documentation and hope that I send the state parameter in the right way and it is forwarded to the callback server after a user logs in.
Now my question is:
Is the documentation correct and the state parameter needs to be added to the authorization header like in "new_headers" above and I just do sth wrong here. If so what am I doing wrong here?
Or is the documentation misleading as simply adding the state parameter as a normal query parameter to the request token url like this "https://123456.restlets.api.netsuite.com/rest/requesttoken?state=eyJ0..." is correct?
I would really appreciate some help here!
Best regards,
JayKay

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.

SOAP client in python, how to replicate with XML

I am using suds to send XML and I got my request working, but I'm really confused by how to replicate my results using XML. I have the XML request that my suds client is sending by using:
from suds.client import Client
ulr = "xxxxxxx"
client = Client(url)
...
client.last_received.str()
but I'm not sure where I would send that request to if I was using the requests library. How would I replicate the request from the suds client in a python request?
Most SOAP APIs are just over plain HTTP, use POST - and therefore are easily mimicked with any standard HTTP client such as Requests.
First look here to see how to view the headers and body that suds is sending - it is then a matter of replicating these headers/XML body and passing them into the Requests library.
One defining characteristic in 99% of all HTTP SOAP API's is that your request is going to the same end-point for each request (for example 'http://yyy.com:8080/Posting/LoadPosting.svc), and the actual action is specified in the header using SOAPAction header). Contrast this to a RESTful API where the action is implied with the verb + end-point you call (POST /user, GET /menu etc.)

Yggdrasil authentication with Python

I decided to try to make an automated login script for Minecraft. However, the new authentication API is stumping me. I can't find any mentions of the new functionality of the API on here. This is my code as it stands:
import requests
import json
data = json.dumps({"agent":{"name":"Minecraft","version":1},"username":"abcdef","password":"abcdef","clientToken":""})
headers = {'Content-Type': 'application/json'}
r = requests.post('https://authserver.mojang.com', data=data, headers=headers)
print (r.text)
Unfortunately, this returns:
{"error":"Method Not Allowed","errorMessage":"The method specified in the request is not allowed for the resource identified by the request URI"}
According to this resource on request format, this error means that I didn't correctly send a post request. However, I clearly declared requests.post(), so my first question is how am I incorrect, and what is the correct way to go about this?
My second question is, since I'm relatively new to Python and JSON, how would I replace the username and password fields with my own data, inside a variable?
You haven't specified an endpoint in your POST request, for example:
https://authserver.mojang.com/authenticate
The root of the website probably does not accept POST requests
http://wiki.vg/Authentication#Authenticate

Using headers with the Python requests library's get method

So I recently stumbled upon this great library for handling HTTP requests in Python; found here http://docs.python-requests.org/en/latest/index.html.
I love working with it, but I can't figure out how to add headers to my get requests. Help?
According to the API, the headers can all be passed in with requests.get():
import requests
r=requests.get("http://www.example.com/", headers={"Content-Type":"text"})
This answer taught me that you can set headers for an entire session:
s = requests.Session()
s.auth = ('user', 'pass')
s.headers.update({'x-test': 'true'})
# both 'x-test' and 'x-test2' are sent
s.get('http://httpbin.org/headers', headers={'x-test2': 'true'})
Bonus: Sessions also handle cookies.
Seems pretty straightforward, according to the docs on the page you linked (emphasis mine).
requests.get(url, params=None, headers=None, cookies=None, auth=None,
timeout=None)
Sends a GET request.
Returns Response object.
Parameters:
url – URL for the new
Request object.
params – (optional)
Dictionary of GET Parameters to send
with the Request.
headers – (optional)
Dictionary of HTTP Headers to send
with the Request.
cookies – (optional)
CookieJar object to send with the
Request.
auth – (optional) AuthObject
to enable Basic HTTP Auth.
timeout –
(optional) Float describing the
timeout of the request.
Go to http://myhttpheader.com
copy attributes - typically 'Accept-Language' and 'User-Agent'.
Wrap them in the dictionary:
headers = { 'Accept-Language' : content-copied-from-myhttpheader,
'User-Agent':content-copied-from-myhttpheader}
pass headers in your request
requests.get(url=your_url,headers=headers)

Categories

Resources