python requests authentication provides multiple mechanisms for authentication to web service endpoints, including basic auth, X.509 certificate authentication, and authentication with a bearer token (JWT or OAuth2 token). This article will cover the basic examples for authenticating with each of these and using python requests to login to your web service.
python requests basic auth
To authenticate with basic auth using the python requests module, start with the following example python script:
import requests
basicAuthCredentials = ('user', 'pass')
response = requests.get('https://example.com/endpoint', auth=basicAuthCredentials)
An alternative to this approach is to just use the python requests authorization header for basic auth:
'Authorization' : 'Basic user:pass'
python requests ignore ssl
To ignore SSL verification of the installed X.509 SSL certificate, set verify=False. For example, in a python requests GET request to ignore ssl:
requests.get('https://example.com', verify=False)
The verify=False
parameter in the get
method declares that the python requests call must ignore ssl and proceed with the api call. This may be necessary in the event of a self signed certificate in certificate chain on the server being connected to. The cause may also be an expired certificate or some other certificate not trusted by your python application by default.
python requests certificate verify failed
If you get the python requests ssl certificate_verify_failed error, the cause is that the certificate may be expired, revoked, or not trusted by you as the caller. If you are in a test environment then it may be safe to set verify=False on your call, as explained above. If you are in a production environment then you should determine whether or not you should trust the root certificate of the trust chain being sent by the server. You may explicitly set this in your call, for example:
requests.get('https://example.com', verify='truststore.pem')
The ssl certificate_verify_failed error is not an error you should simply ignore with thoroughly thinking through the implications.
python requests certificate
python requests authentication with an X.509 certificate and private key can be performed by specifying the path to the cert and key in your request. An example using python requests client certificate:
requests.get('https://example.com', cert=('/path/client.cert', '/path/client.key'))
The certificate and key may also be combined into the same file. If you receive an SSL error on your python requests call, you have likely given an invalid path, key, or certificate in your request.
python requests authorization bearer
The python requests authorization header for authenticating with a bearer token is the following:
'Authorization': 'Bearer ' + token
For example:
import requests
headers = {'Authorization': 'Bearer ' + token}
response = requests.get('https://example.com', headers=headers)
The bearer token is often either a JWT (Javascript web token) or an OAuth2 token for python requests using oauth2.
To generate and sign a JWT with python and a private key, here is an example. The JWT token generated from this python code snippet may then be passed as the bearer token.
import jwt
import time
# Open private key to sign token with
with open('key.pem', 'r') as f:
key = f.read()
# Create token that is valid for a given amount of time.
now = time.time();
claims = {
'iss': '',
'sub': '',
'iat': int(now),
'exp': int(now) + 10 * 60
}
token = jwt.encode(claims, key, algorithm='RS256')
It is also possible to load the private key directly from a Keystore using the pyOpenSSL dependency. Here is a code sample using python requests jwt authentication with a Keystore. Similar to the example above, you can pass in the generated JWT as the bearer token in your python requests REST call.
#!/usr/bin/env python3
import os
import sys
import time
from OpenSSL import crypto
from jwt import JWT
from jwt.jwk import RSAJWK
with open('keystore.p12', 'rb') as f:
p12 = crypto.load_pkcs12(f.read(), bytes('changeit', 'utf-8'))
key = RSAJWK(p12.get_privatekey().to_cryptography_key())
# Create authentication token
now = int(time.time())
claims = {
'iss': '',
'sub': '',
'iat': int(now),
'exp': int(now) + 10 * 60
}
jwt = JWT()
token = jwt.encode(claims, key, alg='RS256')
print(token)
If you would like to see more examples of how to authenticate to REST web services with basic auth, bearer tokens (JWTs or OAuth2), or a private key and certificate leave us a comment.
Conclusion
This article has demonstrated how to use python requests with an x509 client certificate, python requests with a cert and key, and general authentication methods. Please leave us a comment if you have any questions on how to authenticate with a cert and key using python requests.
Leave a Reply