Python Network Programming HTTP Authentication
Python Network Programming HTTP Authentication
Authentication is the process of determining whether a request originates from a valid user with the necessary permissions to use the system. In the world of computer networks, this is a very important requirement, as many systems constantly interact with each other, and mechanisms are needed to ensure that only valid interactions occur between these programs.
The Python module named requests has built-in functionality for calling various APIs provided by service network applications along with user credentials. These credentials must be embedded in the calling program. If the API authentication succeeds, a valid login occurs.
Installing requests
We install the required Python module named requests to run the authentication program.
pip install requests
Authenticating to Github
Below we see a simple authentication mechanism involving only a username and password. A successful response indicates that the login was valid.
import requests
r = requests.get('https://api.github.com/user', auth=('user', 'pass'))
print r
Authenticating with Twitter
We can also run a program to use the Twitter API and successfully log in using the following code. We use the OAuth1 methods in the requests module to handle the parameters required by the Twitter API. As we can see, the requests module can handle more complex authentication mechanisms, including keys and tokens, rather than just usernames and passwords.
import requests
from requests_oauthlib import OAuth1
url = 'https://api.twitter.com/1.1/account/verify_credentials.json'
auth = OAuth1('YOUR_APP_KEY', 'YOUR_APP_SECRET',
'USER_OAUTH_TOKEN', 'USER_OAUTH_TOKEN_SECRET')
requests.get(url, auth=auth)
When we run the above program, we get the following output −
{
"errors": [
{
"code": 215,
"message": "Bad Authentication data."
}
]
}
But using the appropriate OAuth1 parameter values, you will get a successful response.