Authentication overview
STAPI's authentication mechanisms are designed to secure access to its video infrastructure, including video encoding, hosting, streaming, and analytics services. Implementing robust authentication is a prerequisite for interacting with the STAPI API reference, ensuring that only authorized applications and users can perform actions such as uploading videos, managing live streams, or retrieving analytics data. The choice of authentication method typically depends on the application's architecture and the scope of access required.
For server-to-server interactions where an application acts on its own behalf, STAPI recommends using API keys. These keys provide a straightforward method for backend services to authenticate requests without user involvement. Conversely, for client-side applications, mobile apps, or scenarios requiring user consent and delegated access, STAPI supports OAuth 2.0. This standard protocol enables secure authorization flows, allowing users to grant limited access to their resources without exposing their credentials directly to the client application.
Regardless of the chosen method, all interactions with the STAPI API must occur over HTTPS (TLS-encrypted connections). This requirement protects credentials and data in transit from eavesdropping and tampering, aligning with general security best practices for web APIs, as outlined by the Mozilla Web Security documentation on TLS.
Supported authentication methods
STAPI supports two primary authentication methods: API Keys and OAuth 2.0. Each method is suited for different integration patterns and security requirements.
API Keys
API keys are unique, secret tokens that identify and authenticate requests from your application to the STAPI API. They are typically used for server-side integrations where the key can be securely stored and managed. When using API keys, your application includes the key in the header of each API request. STAPI uses this key to verify the origin and authorization of the request against your account's permissions.
- Mechanism: Passed as a header (
X-STAPI-API-Key) or a query parameter (less recommended for sensitive keys). - Use Cases: Server-to-server communication, backend services, batch processing, cron jobs, internal tools.
- Security Considerations: Must be kept confidential. Compromised API keys can lead to unauthorized access.
OAuth 2.0
OAuth 2.0 is an industry-standard protocol for authorization that enables third-party applications to obtain limited access to an HTTP service, either on behalf of a resource owner (user) or by allowing the client to obtain access on its own behalf. STAPI implements OAuth 2.0 to facilitate secure access for client-side applications, mobile applications, and scenarios where user consent is required for delegated access to video resources.
STAPI's OAuth 2.0 implementation typically follows the Authorization Code Grant flow, which is recommended for web applications. Other flows, such as Client Credentials Grant, may be available for specific server-to-server scenarios where the client application acts on its own behalf without a user context.
- Mechanism: Involves an authorization server, resource owner, client application, and resource server. Access tokens are issued and included in requests.
- Use Cases: Single Sign-On (SSO), mobile applications, web applications requiring user consent, integrations with other platforms.
- Security Considerations: Requires careful management of redirect URIs and client secrets. Access tokens have limited lifespans and can be refreshed. The OAuth 2.0 specification provides detailed guidance on implementation.
Summary of Authentication Methods
| Method | When to Use | Security Level |
|---|---|---|
| API Key | Server-side applications, internal tools, backend services where the key can be securely stored. | Medium to High (depends on key management) |
| OAuth 2.0 | Client-side applications, mobile apps, user-facing web apps, delegated access requiring user consent. | High (token-based, scope-limited, revocable) |
Getting your credentials
To begin authenticating with STAPI, you will need to obtain the necessary credentials from your STAPI account dashboard. The process varies slightly depending on whether you require an API key or wish to set up an OAuth 2.0 application.
Getting API Keys
- Sign up or Log in: Access your STAPI account or create a new one.
- Navigate to API Settings: In the dashboard, locate the "API Keys" or "Developers" section. The exact path may vary slightly but is typically under account settings or a dedicated API management area as described in the STAPI documentation.
- Generate New Key: Click on the "Generate New API Key" button. You may be prompted to provide a name or description for the key, which helps in identifying its purpose later.
- Copy and Store Securely: Once generated, the API key will be displayed. It is crucial to copy this key immediately and store it in a secure location, such as an environment variable, a secrets manager, or a configuration file protected by strict access controls. For security reasons, STAPI may only display the full key once.
Setting up OAuth 2.0 Applications
- Sign up or Log in: Access your STAPI account.
- Navigate to Applications/OAuth Clients: Within the dashboard, find the "Applications," "OAuth Clients," or similar section.
- Register New Application: Click on "Register New Application" or "Create OAuth Client." You will typically need to provide the following details:
- Application Name: A human-readable name for your application.
- Redirect URIs: One or more URLs to which STAPI will redirect the user after they authorize your application. These must be exact matches to prevent phishing attacks.
- Application Type: (e.g., "Web Application," "Native/Mobile App").
- Description: A brief explanation of your application's purpose.
- Obtain Client ID and Client Secret: Upon registration, STAPI will provide you with a Client ID and, for confidential clients, a Client Secret. The Client ID is public, but the Client Secret must be kept confidential and handled with the same care as an API key.
- Configure Scopes: Define the specific permissions (scopes) your application requires. Scopes limit the access an application has to a user's data or account, adhering to the principle of least privilege.
Authenticated request example
Here is an example of an authenticated request using an API key with the STAPI API. This Python example fetches a list of videos from your account.
import os
import requests
# Retrieve API Key from environment variable for security
STAPI_API_KEY = os.environ.get("STAPI_API_KEY")
if not STAPI_API_KEY:
raise ValueError("STAPI_API_KEY environment variable not set.")
BASE_URL = "https://api.stapi.io/v1"
ENDPOINT = f"{BASE_URL}/videos"
headers = {
"X-STAPI-API-Key": STAPI_API_KEY,
"Content-Type": "application/json"
}
try:
response = requests.get(ENDPOINT, headers=headers)
response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
videos = response.json()
print("Successfully fetched videos:")
for video in videos["data"]:
print(f" - ID: {video['id']}, Title: {video.get('title', 'N/A')}, Status: {video.get('status', 'N/A')}")
except requests.exceptions.HTTPError as http_err:
print(f"HTTP error occurred: {http_err} - {response.text}")
except requests.exceptions.ConnectionError as conn_err:
print(f"Connection error occurred: {conn_err}")
except requests.exceptions.Timeout as timeout_err:
print(f"Timeout error occurred: {timeout_err}")
except requests.exceptions.RequestException as req_err:
print(f"An unexpected error occurred: {req_err}")
For OAuth 2.0, the process involves obtaining an access token through an authorization flow and then including this token in the Authorization header (e.g., Authorization: Bearer YOUR_ACCESS_TOKEN) for subsequent API calls. STAPI's developer documentation provides specific examples and SDK usage for OAuth 2.0.
Security best practices
Adhering to security best practices is essential when integrating with STAPI to protect your account, data, and users.
- Protect API Keys and Client Secrets:
- Environment Variables: Store API keys and client secrets as environment variables on your server, rather than hardcoding them in your application's source code.
- Secrets Management: Utilize dedicated secrets management services (e.g., AWS Secrets Manager, Google Secret Manager, Azure Key Vault) for production environments.
- Access Control: Implement strict access controls for any system or repository that stores credentials.
- Use HTTPS (TLS) Always: Ensure all API requests are made over HTTPS. STAPI enforces this, but it's important to verify your application's configuration. This encrypts data in transit, preventing unauthorized interception of sensitive information, including credentials and video content.
- Implement Least Privilege:
- API Keys: If STAPI offers granular permissions for API keys, configure them with the minimum necessary permissions required for your application's function.
- OAuth Scopes: For OAuth 2.0 applications, request only the essential scopes. This limits the damage if your access token is compromised.
- Rotate Credentials Regularly: Periodically generate new API keys and revoke old ones. While STAPI may not enforce this, it is a recommended security practice to mitigate risks associated with long-lived credentials.
- Validate Redirect URIs (OAuth 2.0): For OAuth 2.0, ensure that the redirect URIs registered with STAPI are precise and controlled. Only allow redirects to URIs that you own and trust to prevent authorization code interception attacks.
- Error Handling and Logging: Implement robust error handling and logging for authentication failures. Monitor for unusual activity or frequent failed authentication attempts, which could indicate an attack. However, avoid logging raw credentials or access tokens.
- Secure Client-Side Storage: For client-side applications using OAuth 2.0, avoid storing access tokens directly in insecure locations like local storage or cookies without proper HttpOnly and Secure flags. Consider using secure server-side sessions or platform-specific secure storage mechanisms where appropriate.
- Stay Updated: Keep your STAPI SDKs and any related security libraries updated to benefit from the latest security patches and improvements.