- Bearer Token (app-only)
- OAuth 2.0 with PKCE
- 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) 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):
- 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.