Learn How to Use Basic, Token & API Key Authentication

Secure your network automation with three essential API authentication methods: basic auth, API keys, and custom tokens—explained with Cisco DevNet examples.


Cisco Automation course – 027 – Utilize common API authentication mechanisms: basic, custom token, and API keys

Watch Full Demo on YouTube:

Introduction

In modern networking and automation environments, especially within Cisco’s ecosystem, robust API authentication is essential. Network APIs allow software to interface with controllers and devices, executing actions that can alter configurations or retrieve sensitive data. As such, these APIs require authentication to ensure that only authorized users or applications can perform operations – much like how a network engineer must log in to a router or switch before making changes. Proper authentication helps prevent unauthorized access that could lead to accidental or malicious changes (for example, an API call deleting critical configurations would have the same impact as a rogue engineer in the CLI).

This blog post will explore three common API authentication mechanisms – Basic Authentication, API Keys, and Custom Token authentication. We’ll discuss how each method works, their advantages and disadvantages, and real-world Cisco use cases (such as Cisco DevNet sandboxes, DNA Center APIs, Meraki Dashboard, etc.). We’ll also provide implementation notes and compare the methods to understand when to use each for secure and effective network automation.

Basic Authentication

Concept and Mechanism: Basic Authentication is one of the simplest HTTP authentication methods and is widely used in many APIs. In HTTP Basic Auth, the client sends an Authorization header with each request, containing the word “Basic” followed by a base64-encoded string of the format username:password. For example, if the username is admin and password is Cisco123, the header will include Authorization: Basic YWRtaW46Q2lzY28xMjM= (where YWRtaW46Q2lzY28xMjM= is the base64 encoding of admin:Cisco123). Web servers or API endpoints decode this header to verify the credentials.

Usage in Cisco Environments: Basic auth is common in many Cisco API scenarios for initial authentication. For instance, Cisco DNA Center’s API uses a token-based system, but the token is obtained by sending a POST request with Basic Authentication to an auth endpoint. Similarly, Cisco Nexus devices that expose the NX-API require HTTP Basic Authentication for every request — the device expects a username and password in the request header and will reject calls without valid credentials. (It’s worth noting that in NX-API, once authenticated, the device may issue a session cookie to streamline subsequent requests, but the credentials still need to be presented unless that session cookie is used.) In Cisco sandbox environments, such as the DNA Center sandbox, you are often provided with a username/password (e.g. devnetuser/Cisco123!) which you use via Basic Auth in Postman or your script to retrieve an API token for further calls.

Security Considerations: The simplicity of Basic Auth comes with security drawbacks. The credentials are only base64-encoded, not encrypted, in transit. If Basic Auth is used over plain HTTP, an attacker could easily intercept the username and password by sniffing the traffic (base64 is trivial to decode). Therefore, Basic Auth should always be used over an HTTPS/TLS connection to ensure the credentials are encrypted on the wire. Even with TLS, another concern is that the client resends the username and password with every single request. This repeated exposure means that if any one request is logged or intercepted, the credentials could be compromised. Basic Auth also does not natively provide a way to enforce account lockouts or multi-factor authentication, and it relies entirely on the strength of the username/password combination. Because of these issues, Basic Auth is generally considered the least secure of the common methods, especially for long-term or production use.

Advantages: The main advantage of Basic Authentication is its simplicity and ubiquity. It’s lightweight and easy to implement – no complex handshakes or token management are required. Many tools (including Postman and the Python requests library) support Basic Auth out-of-the-box. In Postman, you can simply select “Basic Auth” and enter the username and password, and it will add the proper header for you. In Python, you can use the requests library with an HTTPBasicAuth helper: for example,

import requests
from requests.auth import HTTPBasicAuth

url = “https://sandboxdnac.cisco.com/dna/system/api/v1/auth/token”  # DNA Center auth endpoint
response = requests.post(url, auth=HTTPBasicAuth(“devnetuser”, “Cisco123!”))
print(response.status_code, response.text)

This will send the credentials using Basic Auth to the DNA Center sandbox to retrieve a token (if the credentials are correct, the response contains a token string). Because Basic Auth is part of the HTTP standard, virtually all programming languages and API clients support it, making it quick to set up during development or testing.

When to Use Basic Auth: Due to its security limitations, Basic Auth is best used in controlled scenarios: for lab environments, internal tools over secure networks, or one-time quick tests. In Cisco DevNet sandboxes or lab exercises, you might use Basic Auth to authenticate against devices or controllers that don’t yet support more sophisticated methods. For example, some older network devices or simple services use Basic Auth because it’s easy to implement on both client and server. However, in production network automation workflows, you would rarely rely on Basic Auth alone. Instead, you might use it only to obtain a more secure token (as with Cisco DNA Center or Cisco SD-WAN vManage APIs), or you would move to other methods like API keys or tokens for better security.

API Keys

Concept: An API key is a pre-generated secret token (often a long string) that a client provides when making API calls to identify and authenticate itself. In essence, an API key is like a password alternative specific to the API: it proves you have permission to access the API. Typically, API keys are issued by the service to authorized users or applications – for example, you might log into a developer portal and generate an API key that you can then use in your scripts. Critically, an API key should be kept secret just like a password; anyone who obtains the key could potentially use the API with the same privileges as you. If the API is capable of making changes (for instance, a network management API that can change device configurations), a leaked API key could be as dangerous as a leaked admin password.

Transmission Methods: APIs accept keys in various ways. The three common ways to pass an API key are via query string, request header, or cookie:

  • Query string: Include the key in the URL as a parameter. For example:

    GET /some/api/endpoint?api_key=abcdef12345
  • This approach is straightforward – you can paste the key into the URL. However, it’s less secure because URLs can end up in logs or browser history. Example: A Cisco Umbrella DNS query might use an API token in the query string to fetch domain information (though modern practice is moving away from putting secrets in URLs).
  • HTTP Header: Send the key as part of the headers in each request. This is a cleaner approach for scripts and tools. For instance:

    GET /some/api/endpoint HTTP/1.1 
    X-API-Key: abcdef12345
  • Many API providers define a custom header name (like X-API-Key) for this purpose. Some, including Cisco’s newer APIs, use the standard Authorization header with a Bearer token format. For example, Cisco Meraki requires an API key for its Dashboard API, and in the latest version it expects: Authorization: Bearer “API_KEY” in the header of each request. (Older Meraki API versions accepted X-Cisco-Meraki-API-Key: <API_KEY> as a header, which is a similar concept.) Using headers for API keys is convenient when making multiple calls – you configure your client to always send the header, avoiding the need to manually append the key to every URL.
  • Cookie: Some APIs (or web services) allow the client to store the API key in a cookie. The server then reads the cookie on each request to authenticate. For example, the API might expect a cookie like: Cookie: APIKey=abcdef12345. In practice, cookie-based API key usage is less common in pure REST APIs, but it can be encountered in web applications or when using a browser to make API calls. The idea is similar to header-based auth: once the cookie is set (for instance, by a prior login or by manually setting it), it gets sent automatically with subsequent requests.

Each of these methods has its use cases. Query strings are simple for quick tests (you can just hit a URL in a browser if the API allows), but should be avoided for long-term use. Headers are the most common approach in automation scripts and tools like Postman, since they keep authentication data out of the URL. Cookies might appear when the API authentication is piggybacking on a web session (for example, if you log in via a web portal and then use the same session to call APIs).

API Keys in Cisco Platforms: Cisco offers a few APIs that rely on API keys. One notable example is the Cisco Meraki Dashboard API, which is used to manage Meraki wireless, switching, and security devices in the cloud. When using the Meraki API, you generate an API key from the Meraki dashboard (under your user profile) and then use that key in your API calls. With the Meraki API v1, the key is passed in an HTTP header as mentioned (Authorization: Bearer <API_KEY>), aligning with common practice. Another example is the Cisco Umbrella Investigate API, where you obtain an API token (key) from the Umbrella dashboard and use it as a bearer token in API requests. In Cisco DNA Center and similar on-premises controllers, API keys are less common; those systems prefer token-based authentication (discussed in the next section). However, if you use certain Cisco cloud services or older APIs, you may encounter API keys. For instance, some Cisco Webex (Spark) API integrations use a developer-generated token (which is essentially an API key) to allow bots or integrations to access Webex on a user’s behalf.

Security and Flexibility: API keys offer some security benefits over using raw username/password in Basic Auth. For one, you’re not sending your actual user password with each request. The key is a surrogate token that can often be regenerated or revoked without forcing a change to your login credentials. This provides flexibility: you might generate different keys for different applications or projects and revoke one without affecting others. Additionally, the scope of API keys can sometimes be limited – for example, a key might have permissions only for certain APIs, or read-only vs read-write, depending on the platform. That said, API keys should be treated with the same level of secrecy as passwords. If an attacker obtains your key, they can call the API freely, and most API keys do not expire automatically. Unlike session tokens, which are short-lived, a static API key could grant access indefinitely until you manually revoke it. Therefore, it’s critical to store keys securely (for example, in environment variables or vault services, not hard-coded in scripts). The Meraki documentation, for instance, advises saving the API key in an environment variable so that it isn’t exposed in your code.

Implementation Notes: Using API keys in tools is straightforward. In Postman, you can use the “Headers” tab to add the required header (like X-API-Key) and value, or use the “Params” tab for query string keys. Postman also has a feature to store variables (like an environment variable for the API key) so you don’t have to paste the key everywhere. In Python, you would typically add the key to the request. For example, using requests for a header-based key:

headers = {“Authorization”: “Bearer <YOUR_API_KEY>”}
response = requests.get(“https://api.meraki.com/api/v1/organizations”, headers=headers)

This would include the API key in the request. If the API expected a query parameter instead, you could do: requests.get(url, params={“api_key”: API_KEY}). And for a cookie, you could use the cookies parameter or manage a session with requests.Session. Always refer to the API’s documentation for the exact method (header name, parameter name, etc.) expected.

In summary, API keys provide a simple way to authenticate automated clients without handling user passwords on each call. They are especially common in cloud services and when you want to delegate limited access to third-party integrations. However, they must be managed carefully to avoid leakage, and additional measures (like regenerating keys periodically, or combining with token workflows) might be used to mitigate their risks.

Custom Token Authentication

Concept: Token-based authentication (sometimes called “bearer token” auth or session token auth) is a step up in security and convenience over sending credentials for every request. The idea is that a client will authenticate once using valid credentials and in return receive a token – a random and often encrypted or encoded string – that represents its authenticated session. This token is then included in subsequent requests (typically in an HTTP header) instead of the username and password. The server recognizes the token and grants access as long as the token is valid. Because the token is essentially a stand-in for your credentials, anyone bearing the token is treated as you (hence the term “bearer token”), so it must be kept secret just like a password or key.

A token might be a self-contained string like a JWT (JSON Web Token) or just an opaque session identifier that the server tracks. Importantly, tokens are usually temporary – they can be configured to expire after a certain duration for security. Once expired, the client needs to re-authenticate (for instance, by providing username/password again) to get a new token. This time-bound nature limits how long a stolen token can be abused and also reduces the window in which an old token could be replayed.

Why Tokens Improve Security: Custom token authentication addresses several issues of Basic Auth. First, the user’s actual password is not sent repeatedly. It’s transmitted only once (during the initial authentication to get the token), and after that, the token is used. This means if someone intercepts a later request, they get only a token, not the permanent credentials. And if the token has a short lifespan (say 30 minutes or an hour), it greatly limits the damage – the token would soon become invalid. Also, because tokens are often random or encrypted strings, an attacker cannot reverse-engineer them to derive the original password (unlike Basic Auth where the base64 can be decoded to reveal the password). Many implementations also tie tokens to a single user session or client, making them invalid if used from a different IP or after logout, etc. Overall, token-based auth is considered more secure than Basic Auth (and often more secure than static API keys) because of these controls.

Workflow: The typical workflow for token-based auth in a Cisco environment (or any similar system) is: 1. Authentication request: The client sends a request to an authentication endpoint, usually with a POST method. The credentials (username/password or sometimes an API key/secret) are provided in this request. For example, Cisco DNA Center exposes an endpoint /dna/system/api/v1/auth/token where the client must POST with Basic Auth credentials to obtain a token. 2. Token issuance: If the credentials are valid, the server responds with an authentication token. This might be returned in the JSON body (e.g., { “Token”: “<token string>” }) or in a response header. Cisco DNA Center’s API, for instance, returns a token in the X-Auth-Token header of the response upon successful login. 3. Using the token: The client then includes this token in the header of subsequent API calls. Different APIs use different header names or formats. A common approach is the Authorization header with a “Bearer” scheme (e.g., Authorization: Bearer <token>). Cisco DNA Center uses a custom header X-Auth-Token: <token> for API requests. In Cisco SD-WAN vManage, after a successful login, the API sets a session cookie (such as JSESSIONID) which the client must send in subsequent requests – conceptually similar to using a token, but the token is stored in a cookie automatically. 4. Token expiration and refresh: The token remains valid for a set time period. For example, DNA Center tokens are valid for 60 minutes by default. If a client tries to use a token after it expires, the server will reject the request (HTTP 401 Unauthorized), prompting the client to authenticate again and get a new token. In a script, this means you may need to handle a token refresh (e.g., if a request fails due to expiration, re-auth and continue). In a tool like Postman, you would manually re-fetch a token or write a test script to automate refreshing a token when needed.

Real-World Use Cases in Cisco Automation: Many Cisco platforms use token-based authentication as the preferred method: – Cisco DNA Center and Cisco Catalyst Center: As discussed, they issue a token via the /auth/token endpoint. All subsequent API calls require that token in the X-Auth-Token header. This improves security on the controller by not having to handle user passwords on every request. – Cisco SD-WAN (vManage): The vManage REST API requires an initial login (with Basic Auth or a form-based login) which creates a session cookie. That cookie (which contains a session token) must be included in further requests (the Python requests.Session can handle this by storing cookies). The session cookie typically expires after a certain time of inactivity, requiring re-login. – Cisco ACI (APIC): The Cisco APIC (Application Policy Infrastructure Controller for ACI) API similarly uses a login token. You post to /api/aaaLogin.json with credentials, and the response includes a token (and a session cookie called APIC-cookie). Subsequent requests include that cookie or token, rather than resending credentials each time. The APIC token can expire or be invalidated on logout. – Cisco Webex APIs: When integrating with Webex (formerly Cisco Spark), you obtain an OAuth access token (or a developer token) and then use it as a bearer token for API calls. This is more of a standard OAuth flow, but at the usage level it is still a token string that you include with requests. – Cisco Meraki (modern approach): Although Meraki uses an API key for auth, in practice when you set the header Authorization: Bearer <API_KEY>, you’re treating the API key as a token that doesn’t expire. It blurs the line between “API key” and “token,” but it’s worth noting that the usage is identical to bearer tokens – Meraki just chooses not to expire them automatically.

The advantage in all these cases is that automation scripts or applications can authenticate once, then perform many operations without constantly handling sensitive passwords. Network automation often involves running sequences of API calls (for example, retrieving a list of devices, then pushing configurations, then verifying status). Token auth makes this more efficient and secure by maintaining a session. Furthermore, tokens allow the backend to implement additional checks – for instance, tokens can be revoked or scoped. An admin could invalidate a token if suspicious activity is detected without forcing a user to change their password. Or a token could be limited in what it can do (though in many Cisco APIs, the token inherits the full permissions of the user account that generated it).

Implementation Notes: In Postman, you can manage token workflows by creating a dedicated authentication request. You execute the auth request to get the token, then use Postman’s environment variables or scripting feature to store the token and automatically insert it into the header of subsequent requests. For example, after a successful DNA Center auth, you might write a small script in Postman to capture the X-Auth-Token header value and set it as an environment variable, then for all other requests, use that variable in the X-Auth-Token header field. In Python, handling tokens might look like:

# authenticate and get token
auth_resp = requests.post(auth_url, auth=HTTPBasicAuth(user, pwd))
token = auth_resp.json().get(“Token”)  # or auth_resp.headers.get(“X-Auth-Token”)
# use the token in subsequent calls
headers = {“X-Auth-Token”: token}
resp = requests.get(api_url, headers=headers)

If cookies are involved (as in vManage or APIC), you might do:

session = requests.Session()
session.post(login_url, json={“username”: user, “password”: pwd})  # session stores cookie
resp = session.get(some_api_url)  # session will send cookie automatically

Be mindful of token expiration. A long-running automation tool should handle a 401 response by re-authenticating to fetch a fresh token.

Security Best Practices: Always transmit tokens over HTTPS to prevent interception. Treat tokens with the same care as passwords or keys – if someone steals your token, they can act as you until it expires. It’s also good practice to logout or invalidate tokens if the API provides such a mechanism (for example, some systems have a “logout” endpoint that you can call to invalidate your token when you’re done, which is especially important if tokens don’t expire quickly).

Comparing Authentication Methods

Each authentication mechanism – Basic Auth, API Keys, and Token-based – has its place in network automation. Let’s compare them in terms of ease of use, security, and typical use cases within Cisco automation workflows:

  • Basic Authentication: Ease of Use: Easiest to implement. You only need a username and password, and most tools handle the encoding for you. No preliminary requests are needed; every API call just includes the credentials. Security: Weakest if used alone. Even though it can be secure enough when combined with TLS encryption, Basic Auth still exposes your credentials frequently. There’s no expiration (the password is valid until changed) and no granular control – it’s all-or-nothing access to whatever the user account permits. It’s also not suitable for integrations where you might not want to share your personal credentials. Use Cases: Primarily used for quick tests, internal or low-risk APIs, or as the initial step to obtain a token. In Cisco automation, you might use Basic Auth to log in to a sandbox controller to get a token, or when interacting directly with a device’s REST interface that only supports basic auth (e.g., NX-OS NX-API on a Nexus switch). Basic Auth is generally not used for public-facing APIs in Cisco’s cloud products due to its limitations.
  • API Keys: Ease of Use: Very easy as well. Similar to Basic in practice (you include a string in requests), but often easier to manage in scripts since it’s just one key string rather than a username/password pair. No need for an initial login request – the key itself is enough to authenticate each call. Security: Better than Basic in that you’re not exposing a username/password combo and you can often regenerate keys if needed. However, keys are typically long-lived and do not expire automatically, which can be a vulnerability. If a key is leaked, an attacker has potentially unlimited access until the key is noticed and revoked. API keys also usually lack built-in protections like rate limiting or scope unless implemented by the API (some platforms allow creating read-only keys or keys scoped to certain actions, which is a good practice). Also, keys don’t inherently identify a user (they identify an application or account as a whole), so within a team everyone might share one key, making it harder to tell who made what change. Use Cases: Common for cloud services and when you want to allow programmatic access without a full user login process. In Cisco’s world, the Meraki cloud is a perfect example – network administrators can use API keys to let scripts or third-party services manage their Meraki networks without exposing their actual dashboard password. API keys are also used in some Cisco security and collaboration APIs for integrating with external systems. Within enterprise automation workflows, you might use an API key when interacting with Cisco services that provide one, but when dealing with on-prem devices and controllers, you’ll more likely use tokens or Basic Auth since those systems manage user accounts.
  • Custom Token (Bearer Token) Authentication: Ease of Use: Moderately easy, but with an extra step. You have to write code or configure your tool to do the initial authentication handshake (which could be Basic Auth or a special login call) to retrieve the token. This adds a bit of complexity and overhead, especially if tokens expire and need refreshing. Security: Strongest of the three. Tokens are usually random, often short-lived, and can’t be decoded to reveal credentials. The fact that they expire limits how long a stolen token is useful to an attacker. Also, servers can implement measures like token revocation or IP binding (so a token might only be usable from the client that obtained it). The main risk is if someone manages to steal a token, they can use it until it expires (or is revoked) – so your systems should still protect tokens in transit (TLS) and at rest. Overall, token auth provides a good balance of security and usability, and it aligns well with modern security practices (similar concept to OAuth, session management, etc.). Use Cases: Ideal for enterprise controllers and applications where security is paramount. Cisco DNA Center, Cisco vManage, Cisco APIC – essentially any controller that manages significant network infrastructure – use token-based auth by default. It’s also common in any scenario where you need to maintain an authenticated session over multiple requests, like an automation script performing a series of tasks. In addition, if you’re building an application that interacts with Cisco APIs, using token auth means you can manage sessions and possibly implement features like automatic re-authentication when needed. The slight overhead of token management is usually worth the improved security, especially in production environments.

In summary, Basic Auth is best for simplicity or lab use but should be avoided for high-security requirements. API Keys offer a convenient way to access APIs without handling user passwords, suitable for integration scenarios; they improve security somewhat but come with their own risks if not handled properly. Tokens (custom or bearer tokens) are the preferred method for most secure applications and are widely used in modern Cisco platforms – they require a bit more work upfront but provide better protection and control. A general rule in Cisco network automation workflows is to use the method the platform is designed for: e.g., use token auth for controllers like DNA Center, use the provided API key for Meraki cloud, and so on. Always ensure that whichever method you use, it is transported over secure channels (HTTPS) and that secrets (passwords, keys, tokens) are stored securely in your automation code and tools.

Conclusion

API authentication is a fundamental aspect of working with network automation and programmability. As a CCNA Automation (DevNet) Associate, understanding the differences between Basic Auth, API Keys, and Token-based authentication is crucial for designing and consuming APIs in a secure and effective manner. You will encounter all three methods: from simple lab setups using Basic Auth, to cloud services using API keys, to controller-based architectures leveraging token-based sessions. Choosing the appropriate method for a given situation impacts not only the security of your network but also the ease with which you can integrate and automate tasks. Basic Authentication might get you up and running quickly, but for production-grade solutions you’ll lean on API keys or tokens to protect your network resources. Always follow best practices: use encryption (HTTPS), avoid exposing or hard-coding sensitive credentials, and prefer tokens or keys that can be rotated or invalidated over static reusable passwords.

In closing, securing API access in network automation is just as important as securing device access in traditional network management. By mastering these common authentication mechanisms and knowing when to apply each, you lay a strong foundation for building automated solutions that are not only powerful and convenient but also safe and trustworthy. Cisco provides a rich set of APIs across its product portfolio, and nearly all of them require one of these authentication methods – so practicing with Cisco DevNet sandboxes and tools like Postman or Python will reinforce these concepts. As you progress, you’ll also encounter more advanced authentication schemes (OAuth 2.0, SAML, etc.), but the principles learned from Basic Auth, API Keys, and token-based auth will continue to apply. Keep security in mind at every step of your automation journey, and happy coding!


References

DevNet Associate – Cisco

Cisco Certified DevNet Expert (v1.0) Equipment and Software List

DevNet Associate Exam Topics

How to Build an API Request in 3 Ways

  1. Cisco DevNet Associate OCG – Understanding REST API Authentication.
  2. Cisco DNA Center API Documentation – Authentication and Token Usage.
  3. Cisco Meraki Developer Documentation – API Key (Bearer Token) Authentication.
  4. Cisco Nexus 9000 Programmability Guide – NX-API Security (Basic Auth).
  5. Kong HQ API Authentication Guide – Pros and Cons of Basic vs Token vs API Key.

Discover more from IEE

Subscribe to get the latest posts sent to your email.


Discover more from IEE

Subscribe now to keep reading and get access to the full archive.

Continue reading