napalm-automation-community / napalm-asa

napalm-asa
Apache License 2.0
17 stars 13 forks source link

Implement Token Authentication #12

Closed DiogoAndre closed 6 years ago

DiogoAndre commented 6 years ago

Documentation can be found here: https://www.cisco.com/c/dam/en/us/td/docs/security/asa/api/asapedia_rest_api_111.pdf#Token_Authentication_API

wvandeun commented 6 years ago

I kind of have a reference implementation using the Token Authentication API that you could leverage. Here's some quick example code that uses the requests library. I'm using the requests session object to set the X-Auth-Token, so that any subsequent requests using the session have the token set.

I really think you should consider swapping urllib2 for requests. It will also make life easier when working on python3 support.

import requests
from requests.auth import HTTPBasicAuth

def authenticate(ip,port,user,pwd):
    url = 'https://{}:{}/api/tokenservices'.format(ip,port)
    s = requests.Session()
    s.verify = './cacerts.pem'
    r = s.post(url, verify = False, auth=HTTPBasicAuth(user,pwd))

    if r.status_code != 204 and not 'X-Auth-Token' in r.headers.keys():
        print('-- The authentication failed or the server didn\'t return a valid token!')
        return (False,None)

    s.headers.update({'X-Auth-Token':r.headers['X-Auth-Token']})
    print('-- Authentication succeeded!')
    return (True,s)
DiogoAndre commented 6 years ago

Thanks! Yep, really need to replace urllib2. Already working on it actually, I will add an issue for that as a prereq for #7

DiogoAndre commented 6 years ago

Implemented in 424d8c716b8664850167a0da4282f1677a7b975b