Search code examples
pythonopenstack

openstack cannot retrieve authentication token from API


I am trying to retrieve the authentication token from the API using requests library from python. Here is the attempt I have made so far:

def get_token():
    data = { 
      "auth" : {
         "identity" : { 
            "methods" : [ "password" ],
            "password": { 
               "user" : { 
                  "name"  : OS_USERNAME,
                  "domain": { "name": "Default" },
                  "password": OS_PASSWORD
               }
            }
         }
      }   
    }

    r = requests.post(
    OS_AUTH_URL+'/auth/tokens',
      headers = HEADERS,
      json    = data,      # https://stackoverflow.com/questions/9733638
      verify  = False
    )
    print(r.content)
    j = json.loads(r.content)
    return j['token']['user']['id']

I get token in the response :

{
  "token": {
    "issued_at": "2018-07-03T11:03:59.000000Z",
    "audit_ids": [
      "Fg1ywtZBQ1CkigCw70If9g"
    ],
    "methods": [
      "password"
    ],
    "expires_at": "2018-07-03T12:03:59.000000Z",
    "user": {
      "password_expires_at": null,
      "domain": {
        "id": "default",
        "name": "Default"
      },
      "id": "e0dc5beb383a46b98dad824c5d76e719",
      "name": "admin"
    }
  }
}

However, when I am reusing this token to get, for instance, the list of projects :

def get_tenantID():
  r = requests.get(
    OS_AUTH_URL+'/auth/projects',
    headers = HEADERS,
    verify  = False
  )
return r
r = get_token()
HEADERS['X-Auth-Project-Id'] = 'admin'
HEADERS['X-Auth-Token'] = r
r = get_tenantID()

I get this error as if I would not be authenticated:

<Response [401]>
{"error": {"message": "The request you have made requires authentication.", "code": 401, "title": "Unauthorized"}}

Googling around and using openstack token issue command showed me that usually, token are more like:

 gAAAAABaCo1F1CIMVlsTBeuqYH8tm2qR29tbkmUL4vZuhCNPXJI39TQ2YzL6Twoj8fNcAyLe3WhCYW2O1YpbBF0G8mo4bt7Kf0IRsoDOoJ6uWa3RYyJ5SQNoB_5n8EnVXbKPxFYOZ_iFBnaVtL1_XDrGbwsrlDeyy8lZTDdLsqY52pUhFR-7Uow

which is not what I get with get_token.

What am I doing wrong?

Many thanks!


Solution

  • When you use the auth API directly, the token issued comes in the X-Subject-Token header.

    Thus, to retrieve in your python example, you could access the response.headers dict like this:

    token = r.headers['X-Subject-Token']
    

    More info about authentication in the Keystone v3 docs