user3331975
user3331975

Reputation: 2805

Rest call authentication in Python

Sorry for this basic question again, still in learning stages of Python. I am writing a Python script that makes a Rest call which will have basic authentication headers included. In this example, the user is luke and password is mypasswd. Since the password is written in clear text, is there a way to encrypt the password within the script or move authentication outside the script in a more secure way? What is the recommended way of authenticatiion when using Rest with Python?

import urllib2
import base64
import xml.etree.ElementTree as ET

weblink = "https://192.168.1.1/user"
auth = base64.b64encode("luke:mypasswd")
headers = {"Authorization":"Basic " + auth}

Upvotes: 0

Views: 726

Answers (2)

Milos Miletic
Milos Miletic

Reputation: 500

my recommendation is to use requests package.(pip install requests). http://docs.python-requests.org/en/latest/ Regarding the security of passwords, you can use Global variables perhaps, or some text file with adequate permissions. In linux terminal or .bashrc file: export mypasswd="*******"

import os
import base64
import requests
weblink = "https://192.168.1.1/user"
mypasswd = os.getenv("mypasswd")
auth = base64.b64encode("luke:"+str(mypasswd))
headers = {"Authorization":"Basic " + auth}
#In headers you can have some more properties as Content-Type or so on...
#next would be to call the http method you need(GET,POST,PUT,DELETE)
resp = requests.get(weblink,headers=headers)
print resp.text
print resp.status_code

Upvotes: 0

Tasos Vogiatzoglou
Tasos Vogiatzoglou

Reputation: 2453

You'll have to put somewhere the credentials, so I think you are worried about distributing the credentials with your script. This could be solved by

1) Using a configuration file where you'd store the credentials (https://docs.python.org/2/library/configparser.html)

2) Specify them at the command line

3) Specify them through environment variables.

Upvotes: 1

Related Questions