code base 5000
code base 5000

Reputation: 4102

urllib2 custom handler for token security

I have a python 2.7 project that needs to leverage the python 2.7 urllib2 libraries to connect to a token authentication REST endpoint. The form parameters are as such:

{
   "username" : "<my username>",
   "password" : "<my password",
   "expiration" : <time in minutes>,
   "referer" : "<referer url>"
   "f" : "json"
}

I know I can do a simple POST to get the values back over https but I was wondering, can you extend the urllib2.BaseHandler class to encompass this process?

I believe to do this the handler would have to know the following:

  1. Url of token endpoint
  2. referer
  3. username/password

Can you customize a handler this much? If so, can someone point to an example of how to do this?

Thank you

Upvotes: 2

Views: 447

Answers (2)

Sandeep
Sandeep

Reputation: 29341

It is very easy with python-requests library.

import requests
from requests.auth import HTTPBasicAuth

data = {
   "username" : "<my username>",
   "password" : "<my password",
   "expiration" : <time in minutes>,
   "referer" : "<referer url>"
   "f" : "json"
}

response = requests.post(url, data=data)
# If the url requires basic http authentication.
response = requests.post(url, auth=HTTPBasicAuth('user', 'pass'), data=data)
# assert response.ok == True
# response.json()
# response.text

# To perform bearer token authentication use some thing like
auth_header = {'Authorization': 'Bearer ' + access_token}
metadata = requests.get(
    API_URL + '/v1/users/self', headers=auth_header).json()

Upvotes: 0

Vikas Madhusudana
Vikas Madhusudana

Reputation: 1482

Define a Handler

import urllib2
import urllib


class ExtendedHandler(urllib2.BaseHandler)
        def __init__(self):
            print "create object"


        def https_request(self,req):
            print "Got a request"
            req.add_data(urllib.urlencode({'username': '<username>', 'password': '<password>', 'expiration': "<time>", 'referer': "<referer>", "f" :"json"}))
            return req

You can remove the print statements these are just for debugging

How to use the above Handler.

create a openerDirector

opener = urllib2.build_opener(ExtendedHandler())
opener.open("your httpsurl")

Upvotes: 1

Related Questions