PASTA+ authentication with Python Requests
PASTA+ is a environmental data repository software ecosystem. It allows user access to upload and read data content through a REST API. Some calls (e.g., data upload) require an authenticated session. Authentication can be performed using either HTTP basic authentication (using the Authorization header) that contains user credentials or by providing a custom authentication token, which is returned in a Cookie when using the HTTP basic authentication. The following Python code provides an example of PASTA+ authentication using both HTTP and token-based methods.
This first code block sets up LDAP-style credentials and the target URL for use in the HTTP basic authentication to PASTA+, which is executed by the request.get
function call.
import requests
# Setup user credentials
dn = 'uid=EDI,o=EDI,dc=edirepository,dc=org'
pw = 'SECRET'
url = 'https://pasta.lternet.edu/package/eml'
# Perform HTTP basic authentication and pull token from cookie
r = requests.get(url, auth=(dn,pw))
token = r.cookies['auth-token']
This second code block reuses the authentication token, provided by PASTA+ in the above call, within a cookie, which is again sent to PASTA+ in the request.get
function call.
# Reuse auth-token in cookie for token-based authentication
cookies = {'auth-token':token}
r = requests.get(url, cookies=cookies)
PASTA+ authentication is achieved using either method, but the second authentication token approach is much more efficient once the token is obtained. Note that the token is not persistent and has a relatively short TTL.