Implementing and Operating Cisco Enterprise Network Core Technologies (ENCOR) v1.2AutomationMedium
A network engineer is writing a Python script to interact with a Cisco device using a REST API. The API endpoint requires the use of HTTP Basic Authentication. Which of the following code snippets correctly demonstrates how to implement HTTP Basic Authentication using the Python 'requests' library?
- Aresponse = requests.get(url, json={'username': 'username', 'password': 'password'})
- Bresponse = requests.get(url, headers={'Authorization': 'Bearer token'})
- Cresponse = requests.get(url, params={'user': 'username', 'pass': 'password'})
- Dresponse = requests.get(url, auth=('username', 'password'))
Show answer & explanationAnswer & explanation
Correct answer: D. response = requests.get(url, auth=('username', 'password'))
The Python 'requests' library provides a convenient 'auth' parameter for handling various types of HTTP authentication, including Basic Authentication. By passing a tuple (username, password) to the 'auth' parameter, 'requests' automatically constructs and sends the appropriate 'Authorization: Basic <base64_encoded_credentials>' header.
Why the other options are wrong
- A. This attempts to send credentials in the JSON body, which is not how HTTP Basic Authentication is implemented; it's typically sent in the Authorization header.
- B. This snippet demonstrates Bearer Token authentication, not HTTP Basic Authentication.
- C. This attempts to send credentials as URL parameters, which is insecure and not how HTTP Basic Authentication works.
requests Library Basic Auth
The 'requests' Python library simplifies HTTP Basic Authentication by allowing a (username, password) tuple to be passed to the 'auth' parameter of request methods.
- Automatically base64 encodes credentials.
- Sets the 'Authorization: Basic' header.
- Securely handles credentials within the library.
Memory trick: Requests 'auth' parameter is the key to 'basic' authentication.