- Bearer Token (app-only)
- OAuth 2.0 with PKCE
- OAuth 1.0a (User Context)
- Bearer Token: Use this for read-only access for endpoints that support app-auth (e.g., searching Post’s, streaming endpoints).
- OAuth 2.0 PKCE: Secure authentication for scope-based, user-authorized access (e.g. getting authenticated user’s Post non_public metrics)
- OAuth 1.0a: Legacy authentication for user-specific operations (e.g., posting on behalf of a user, managing lists) Obtain credentials from the X Developer Portal. You’ll need an approved developer account and an app with appropriate permissions (e.g., Read + Write).
Creating a Client
All authentication flows create aClient instance:
1. Bearer Token (App-Only)
For read-only operations without user context. Steps:- In the Developer Portal, generate a Bearer Token for your app.
- Pass it to the
Client. Example:
2. OAuth 2.0 with PKCE (User Context)
This example shows how to use OAuth 2.0 with Proof Key for Code Exchange (PKCE). Use this for user-specific access (e.g. posting on behalf of a user), uploading media for a user etc.). Steps:- In the developer portal, register your app with a redirect URI (e.g.,
http://localhost:8080/callback). - Get Client ID (no secret needed for PKCE).
- Initiate the flow, direct user to auth URL and handle callback. Example (using a web server for callback):
3. OAuth 1.0a (User Context)
For legacy applications or specific use cases that require OAuth 1.0a authentication: Steps:- In the Developer Portal, get your API Key and API Secret.
- If you already have access tokens, use them directly. Otherwise, complete the OAuth 1.0a flow to obtain them.
- Create an OAuth1 instance and pass it to the Client. Example (with existing access tokens):
- Never hardcode secrets in production; use environment variables or secret managers (e.g.,
os.getenv("X_BEARER_TOKEN")). - For PKCE, ensure HTTPS for redirect URIs in production.
- The SDK validates tokens and raises
xdk.AuthenticationErroron failures. For detailed code examples using the Python XDK, check out our code samples GitHub repo.