Authentication overview
Mistral AI employs a straightforward authentication mechanism to control access to its suite of large language models, including Mistral Large, Mistral Small, and Mistral Tiny, as well as its embedding models. The primary method for authenticating requests to the Mistral AI API is through the use of API keys. These keys serve as bearer tokens, which must be included in the header of every API request to verify the identity of the client application and authorize its access to the requested resources.
This approach is common among API providers for its simplicity and effectiveness. When an API key is presented, the Mistral AI infrastructure verifies its validity and permissions before processing the request, ensuring that only legitimate and authorized users can consume the service. All communications with the Mistral AI API must occur over HTTPS, providing encryption in transit to protect the confidentiality and integrity of both the API key and the data exchanged. This secure communication channel is a fundamental component of modern API security, mitigating risks such as man-in-the-middle attacks and eavesdropping, as outlined in web security best practices for Transport Layer Security.
Supported authentication methods
Mistral AI primarily supports API key authentication. This method is a widely adopted standard for web services due to its ease of implementation and management for both developers and API providers. The API key acts as a secret token that grants access to the associated account's resources and operations.
API Key (Bearer Token)
When making requests to the Mistral AI API, your API key must be provided in the Authorization HTTP header, prefixed with Bearer. This is the standard way to implement Bearer Token authentication, where the token itself is the credential.
When to use: API key authentication is suitable for most server-side applications, command-line tools, and backend services that interact with Mistral AI. It is the recommended and currently sole supported method for programmatic access to the Mistral AI API (Mistral AI official documentation).
Security level: Moderate to high, depending on how the API key is managed. When API keys are securely stored and transmitted over HTTPS, they provide a robust layer of authentication. However, their security is entirely dependent on keeping the key secret. Compromise of an API key can lead to unauthorized access and potential abuse of the associated account's resources.
Comparison of Authentication Methods
| Method | Description | When to Use | Security Level |
|---|---|---|---|
| API Key (Bearer Token) | A secret string passed in the Authorization: Bearer header. |
Server-side applications, backend services, script-based integrations. | Moderate-High (dependent on key management and HTTPS usage). |
| OAuth 2.0 | Authorization framework allowing third-party applications to obtain limited access to an HTTP service. | Not currently supported by Mistral AI for API access. | High (delegated authorization, token expiration). |
| Basic Authentication | Username and password encoded in Base64 and sent in the Authorization: Basic header. |
Not currently supported by Mistral AI for API access. | Lower (credentials sent directly, less flexible). |
Getting your credentials
To obtain an API key for Mistral AI, you typically follow these steps:
- Sign Up/Log In: Navigate to the Mistral AI platform and either create a new account or log in to an existing one (Mistral AI homepage).
- Access API Key Management: Locate the section within your account dashboard dedicated to API key management. This is often found under settings, developer options, or a specific API section.
- Generate New Key: Within the API key management area, there should be an option to generate a new API key. It's common practice for platforms to allow you to name your keys for easier identification and management, especially if you plan to use multiple keys for different applications or environments.
- Securely Store Your Key: Once generated, the API key will typically be displayed only once. It is crucial to copy this key immediately and store it in a secure location. Best practices include using environment variables, secret management services, or secure configuration files. Do not hardcode API keys directly into your application code or commit them to version control systems like Git.
- Revoke/Rotate Keys: The API key management interface also allows you to revoke existing keys if they are compromised or no longer needed. It is a good security practice to periodically rotate your API keys, generating a new one and replacing the old one in your applications.
For detailed, step-by-step instructions and the exact UI flow, refer to the official Mistral AI documentation, as the platform's interface may evolve.
Authenticated request example
Once you have obtained your Mistral AI API key, you can use it to authenticate your requests. Here are examples using cURL and the Python SDK, demonstrating how to include the API key in the Authorization header.
cURL Example
This cURL command demonstrates how to send a chat completion request to the Mistral AI API, including the API key as a Bearer Token. Replace YOUR_API_KEY with your actual Mistral AI API key.
curl -X POST \
https://api.mistral.ai/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{
"model": "mistral-tiny",
"messages": [{"role": "user", "content": "Hello, what is the capital of France?"}]
}'
Python SDK Example
The Mistral AI Python SDK simplifies API interaction by abstracting the HTTP request details, including authentication. You initialize the client with your API key, and the SDK handles its inclusion in subsequent requests.
from mistralai.client import MistralClient
from mistralai.models.chat_models import ChatMessage
import os
# It's recommended to load your API key from an environment variable
api_key = os.environ.get("MISTRAL_API_KEY")
if not api_key:
raise ValueError("MISTRAL_API_KEY environment variable not set.")
client = MistralClient(api_key=api_key)
messages = [
ChatMessage(role="user", content="What is the primary function of a transformer in deep learning?")
]
chat_response = client.chat(model="mistral-tiny", messages=messages)
print(chat_response.choices[0].message.content)
In this Python example, the API key is retrieved from an environment variable named MISTRAL_API_KEY. This is a recommended practice for keeping sensitive credentials out of source code.
Security best practices
Securing your Mistral AI API keys is paramount to prevent unauthorized access, control costs, and maintain the integrity of your applications. Adhering to these best practices will significantly enhance the security posture of your integrations:
-
Never hardcode API keys: Directly embedding API keys in your source code is a critical security vulnerability. If your code is ever exposed, your API key will be compromised. Instead, use environment variables, configuration files that are not committed to version control, or dedicated secret management services like AWS Secrets Manager or Google Cloud Secret Manager (Google Cloud secret management documentation).
-
Use environment variables: For server-side applications and scripts, loading API keys from environment variables (e.g.,
MISTRAL_API_KEY) is a standard and effective method. This keeps the key separate from the codebase and allows for easy rotation without code changes. -
Implement least privilege: While Mistral AI currently uses a single API key for all operations, in systems with more granular permissions, always configure API keys with the minimum necessary permissions required for the specific task or application. This limits the damage if a key is compromised.
-
Rotate API keys periodically: Regularly generate new API keys and replace old ones in your applications. This practice, known as key rotation, reduces the window of opportunity for a compromised key to be exploited. A common rotation schedule might be every 90 days.
-
Monitor API usage: Keep an eye on your Mistral AI API usage metrics. Unusual spikes in requests or costs can indicate a compromised key or malicious activity. Set up alerts for unexpected usage patterns.
-
Secure your CI/CD pipelines: If your API keys are used in continuous integration/continuous deployment (CI/CD) pipelines, ensure that these keys are stored securely within the CI/CD system's secret management features. Avoid logging API keys or exposing them in build outputs.
-
Protect against client-side exposure: Never embed your API key directly in client-side code (e.g., JavaScript in a web browser, mobile app code) that users can inspect. If your application needs to call Mistral AI from the client side, route these requests through a secure backend server that adds the API key, acting as a proxy.
-
Use HTTPS/TLS: Ensure all communications with the Mistral AI API are performed over HTTPS. This encrypts the data in transit, protecting your API key and other sensitive information from interception. Mistral AI API endpoints enforce HTTPS, making this a default requirement.
-
Implement IP whitelisting (if available): If Mistral AI offers IP whitelisting for API keys, configure it to restrict API access only to requests originating from a list of trusted IP addresses. This adds an additional layer of defense against unauthorized access, even if a key is stolen.
-
Educate your team: Ensure that all developers and team members who handle API keys understand the importance of these security practices and are trained on how to manage credentials securely.