Generate a NASA Earthdata Login Token

import requests
import netrc
from datetime import datetime
import json
import os

Read netrc file to get EDL information

def get_edl_creds():
    nc = netrc.netrc()
    remoteHostName = "urs.earthdata.nasa.gov"
    edl_creds = nc.authenticators(remoteHostName)
    return {'username':edl_creds[0], 'password':edl_creds[2]}

Specify the URLs for generating new tokens, listing available tokens, and revoking available tokens

edl_token_urls = {
    'generate_token':'https://urs.earthdata.nasa.gov/api/users/token',
    'list_token':'https://urs.earthdata.nasa.gov/api/users/tokens',
    'revoke_token': 'https://urs.earthdata.nasa.gov/api/users/revoke_token'
}

Create a hidden directory to store the output json file with EDL tokens

if not os.path.isdir('../../../.hidden_dir'):
    os.mkdir('../../../.hidden_dir')    

Check if a valid token exists or generate a new token

if len(list_tokens := requests.get(edl_token_urls['list_token'], auth=(get_edl_creds()['username'], get_edl_creds()['password'])).json()) < 1:
    #print('No tokens available. Generating new Earthdata Login Token ...')
    generate_token_url = "https://urs.earthdata.nasa.gov/api/users/token"
    generate_token_req = requests.post(edl_token_urls['generate_token'], auth=(get_edl_creds()['username'], get_edl_creds()['password']))
    token = generate_token_req.json()
    with open("../../../.hidden_dir/edl_token.json", "w") as outfile:
        json.dump(token, outfile)
    print(f'Your EDL token information can be found here: {os.path.abspath("../../../.hidden_dir/edl_token.json")}')
elif datetime.strptime(list_tokens[0]['expiration_date'], "%m/%d/%Y") < datetime.now():
    #print('Available token is expired. Generating a new Earthdata Login Token ...')
    revoke_token = requests.post(f"{edl_token_urls['revoke_token']}?token={list_tokens[0]}", auth=(get_edl_creds()['username'], get_edl_creds()['password']))
    generate_token_req = requests.post(edl_token_urls['generate_token'], auth=(get_edl_creds()['username'], get_edl_creds()['password']))
    token = generate_token_req.json()
    with open("../../../.hidden_dir/edl_token.json", "w") as outfile:
        json.dump(token, outfile)
    print(f'Your EDL token information can be found here: {os.path.abspath("../../../.hidden_dir/edl_token.json")}')
else:
    #print('Earthdata Login Token Found ...')
    with open("../../../.hidden_dir/edl_token.json", "w") as outfile:
        json.dump(list_tokens[0], outfile)
    print(f'Your EDL token information can be found here: {os.path.abspath("../../../.hidden_dir/edl_token.json")}')

Resources

  • https://wiki.earthdata.nasa.gov/display/EL/How+to+Generate+a+User+Token
  • https://urs.earthdata.nasa.gov/documentation/for_users/user_token