Authentication
X APIs handle enormous amounts of data. The way we ensure this data is secured for developers and users alike is through authentication. There are a few methods for authentication, each listed below.
Most developers will not need to deal with the complexities surrounding authentication since client libraries automatically handle these difficulties.
You can find a list of available client libraries on our tools and libraries pages >
Authentication methods
OAuth 1.0a User Context
OAuth 1.0a allows an authorized X developer App to access private account information or perform a X action on behalf of a X account.
App only
App only Access Token allows a X developer app to access information publicly available on X.
Basic authentication
Many of X’s enterprise APIs require the use of HTTP Basic Authentication.
OAuth 2.0 Authorization Code Flow with PKCE
OAuth 2.0 User Context allows you to authenticate on behalf of another account with greater control over an application’s scope, and authorization flows across multiple devices.
Please note
Your App’s API Keys and App only Access Token, as well as your personal Access Token and Access Token Secret can be obtained from the X developer Apps section found in the developer portal.
If you would like to make requests on behalf of another user, you will need to generate a separate set of Access Tokens for that user using the 3-legged OAuth flow, and pass that user’s tokens with your OAuth 1.0a User Context or OAuth 2.0 user context requests.
Additional resources
Guides
Learn how to generate tokens and authenticate requests using our integration guides.
API reference
Review our reference guides for our authentication endpoints.
Protect yourself
Make sure you understand the best practices for storing your keys and tokens.
Question?
Visit our FAQs.
Guides
General
Connecting to Twitter API using TLS
OAuth 1.0a
Obtaining user OAuth access tokens
App only
Application-only authentication
Basic authentication
Log in with X
Use Log in with X, also known as Sign in with X, to place a button on your site or application which allows X users to enjoy the benefits of a registered user account in as little as one click. This works on websites, iOS, mobile, and desktop applications.
Features
- Ease of use - A new visitor to your site only has to click two buttons in order to log in for the first time.
- X integration - The Log in with X flow can grant authorization to use X APIs on your users’ behalf.
- OAuth based - A wealth of client libraries and example code are compatible with the Log in with X API.
Available for
- Browsers - If your users can access a browser, you can integrate with Log in with X. Learn about the browser sign in flow.
- Mobile devices - Any web-connected mobile device can take advantage of Log in with X. Learn about the mobile sign in flow.
Implementing Log in with X
The browser and mobile web implementations of Log in with X are based on OAuth. This page demonstrates the requests needed to obtain an access token for the sign in flow.
To use the “Log in with X” flow, please go to your X app settings and ensure that the “Allow this app to be used to Sign in with X?” option is enabled.
This page assumes that the reader knows how to sign requests using the OAuth 1.0a protocol. If you want to know how to sign a request, read the Authorizing a request page.
If you want to check the signing of the requests on this page, the consumer secret used is: L8qq9PZyRg6ieKGEKhZolGC0vJWLw8iEJ88DRdyOg. This value is for test purposes and will not work for real requests.
The three steps for implementing Log in with X through obtaining a request token, redirecting a user, and converting a request token into an access token are listed below.
Step 1: Obtaining a request token
To start a sign-in flow, your X app must obtain a request token by sending a signed message to POST oauth/request_token. The only unique parameter in this request is oauth_callback, which must be a URL-encoded version of the URL you wish your user to be redirected to when they complete step 2. The remaining parameters are added by the OAuth signing process.
Please note - Any callback URL that you use with the POST oauth/request_token endpoint will have to be registered within the X app settings in the developer portal.
Example request (Authorization header has been wrapped):
Your app should examine the HTTP status of the response. Any value other than 200 indicates a failure. The body of the response will contain the oauth_token, oauth_token_secret, and oauth_callback_confirmed parameters. Your app should verify that oauth_callback_confirmed is true and store the other two values for the next steps.
Example response (response body has been wrapped):
Log in with X Resources
Client libraries
The client libraries listed at X libraries will help implement Log in with X. Use the /oauth/authenticate endpoint, as described in the previous steps.
Buttons
X would prefer your application to use the following buttons for consistent branding. Save these images to host on your own servers.
Sign in with X (button style):
Sign in with X (link style):
Authentication best practices
Your API keys and tokens should be guarded very carefully.
These credentials are directly tied to your developer App and those Twitter account that have authorized you to make requests on behalf of them. If your keys are compromised, bad actors could use them to make requests to the Twitter endpoints on behalf of your developer App or its authorized users, which could mean their requests might cause you to hit unexpected rate limits, use up your paid access allotment, or even cause your developer App to be suspended.
The following sections include best practices that should be considered when managing your API keys and tokens.
Regenerate API keys and tokens
In the event that you believe that your API keys has been exposed, you should regenerate your API keys by following these steps:
- Navigate to the developer portal’s “Projects and Apps” page.
- Click on the “Keys and tokens” icon (🗝 ) next to the relevant App.
- Click on the “Regenerate” button next to the set of keys and tokens that you would like to regenerate.
If you would prefer to regenerate your Access Tokens or Bearer Tokens programatically, you can do so using our authentication endpoints.
- If you would like to regenerate your Access Tokens, you must invalidate your tokens using the POST oauth/invalidate_token endpoint, then regenerate your tokens using the 3-legged OAuth flow.
- If you would like to regenerate your Bearer Token, you must invalidate your token using the POST oauth2/invalidate_token endpoint, then regenerate your token using the POST oauth2/token endpoint.
Having a central file for your secrets
Having a file such as .ENV file or any other sort of .yaml file to contain your secrets is an option that could be helpful but be sure to have a strong .gitignore file that can prevent you from accidentally committing these to a git repository.
Environment variables
Writing code that utilizes environment variables might be helpful.
An example of this is as follows written in Python:
import os
consumer_key = os.environ.get("CONSUMER_KEY")
consumer_secret = os.environ.get("CONSUMER_SECRET")
Inside of your terminal you would want to write something like this:
export CONSUMER_KEY='xxxxxxxxxxxxxxxxxxx'
export 'CONSUMER_KEY'='xxxxxxxxxxxxxxxxxxxxxxx'
Source code and version control
The most common security mistakes made by developers are having API keys and tokens committed to source code in accessible version control systems like GitHub and BitBucket. Many of these code repositories are publicly accessible. This mistake is made so often in public code repositories that there are lucrative bots that scrape for API keys.
- Use server environment variables. By storing API keys in environment variables, you keep them out of your code and version control. This also allows you to use different keys for different environments easily.
- Use a configuration file excluded from source control. Add the filename to your .gitignore file to exclude the file from being tracked by version control.
- If you remove the API keys from your code after you have used version control, the API keys are likely still accessible by accessing previous versions of your codebase. Regenerate your API keys, as described in the next section.
Databases
If you need to store your access tokens in a database, please keep the following in mind:
- Restrict access to the database in a way such that the access tokens are only readable by the owner of the token.
- Restrict edit/write privileges to the database table for access tokens - this should be automated with the key management system.
- Encrypt access tokens before storing in any data stores.
Password management tools
Password management tools such as 1password or Last Pass can be helpful in keeping your keys and tokens in secure place. You might want to avoid sharing these in side of a shared team password management tool.
Web storage & cookies
There are two types of web storage: LocalStorage and SessionStorage. These were created as improvements to using Cookies since the storage capacity for web storage is much higher than Cookie storage. However, there are different pros and cons to each of these storage options.
Web Storage: LocalStorage
Anything stored in local web storage is persistent. This means that the data will persist until the data is explicitly deleted. Depending on the needs of your project, you might view this as a positive. However, you should be mindful of using LocalStorage, since any changes/additions to data will be available on all future visits to the webpage in question. We would not usually recommend using LocalStorage, although there may be a few exceptions to this. If you decide to use LocalStorage, it is good to know that it supports the same-origin policy, so all data stored here will only be available via the same origin. An added performance perk of using LocalStorage would be a resulting decrease in client-server traffic since the data does not have to be sent back to the server for every HTTP request.
Web Storage: SessionStorage
SessionStorage is similar to LocalStorage, but the key difference is that SessionStorage is not persistent. Once the window (or tab, depending on which browser you are using) that was used to write to SessionStorage is closed, the data will be lost. This is useful in restricting read access to your token within a user session. Using SessionStorage is normally more preferable than LocalStorage when thinking in terms of security. Like LocalStorage, the perks of same-origin policy support and decreased client-server traffic apply to SessionStorage as well.
Cookies
Cookies are the more traditional way to store session data. You can set an expiration time for each cookie, which would allow for ease of revocability and restriction of access. However, the client-server traffic would definitely increase when using cookies, since the data is being sent back to the server for every HTTP request. If you decide to use cookies, you need to protect against session hijacking. By default, cookies are sent in plaintext over HTTP, which makes their contents vulnerable to packet sniffing and/or man-in-the-middle attacks where attackers may modify your traffic. You should always enforce HTTPS to protect your data in transit. This will provide confidentiality, integrity (of the data), and authentication. However, if your web application or site is available both through HTTP and HTTPS, you will also want to use the ‘Secure’ flag on the cookie. This will prevent attackers from being able to send links to the HTTP version of your site to a user and listening in on the resulting HTTP request generated.
Another secondary defense against session hijacking when using cookies would be to validate the user’s identity again before any high-impact actions are carried out. One other flag to consider for improving the security of your cookies would be the ‘HttpOnly’ flag. This flag tells the browser that the cookie in question shall only be accessible from the server specified. Any attempts made by client-side scripts would be forbidden by this flag, therefore helping to protect against most cross-site scripting (XSS) attacks.
Connecting to Twitter API using TLS
TLS connections are required in order to access Twitter API endpoints. Communicating over TLS preserves user privacy and security by protecting information between the user and the Twitter API as it travels across the public Internet. Connections to the Twitter API require TLS version 1.2.
Verification
Use an up-to-date root store
It’s important that your application or library use a trustworthy and up-to-date root store when verifying the Twitter certificate. Where possible, using the root store provided by your operating system may be the simplest approach here. Alternatively, the Mozilla (NSS) root store is well maintained in a public and transparent manner. Curl also provides a version of this store in PEM format.
Twitter currently issues the bulk of our certs from the DigiCert High Assurance EV Root CA, but this is not true for 100% of Twitter-related certificates and may not hold true forever, so trusting only the currently-used Digicert roots may lead to issues with your app in the future.
Check CRLs and the OCSP status
Many applications do not check the Certificate Revocation List for returned certificates or rely on the operating system to do so. Ensure that your application or TLS library is configured to force CRL and OCSP (Online Certificate Status Protocol) verification before accepting Twitter’s certificate.
When showing Tweets that contain media, use the media_url_https
attribute for the HTTPS URLs to use when showing images. In the future, all URLs served from API endpoints will provide HTTPS paths.
Provide an indication of security status
If possible, you should show an indication of the current status between your application and Twitter. Some web browsers indicate this by offering a Lock Icon, while others indicate the current connection state with descriptive messaging.
X API v2 authentication mapping
The following chart illustrates which v2 endpoints map to what authentication methods.
Endpoint | OAuth 1.0a User Context | **OAuth 2.0 **App Only | OAuth 2.0 Authorization Code with PKCE |
Tweet lookup Retrieve multiple Tweets with a list of IDs GET /2/tweets Retrieve a single Tweet with an ID GET /2/tweets/:id | ✅ | ✅ | ✅ Scopes: tweet.read users.read |
Manage Tweets Post a Tweet POST /2/tweets Delete a Tweet DELETE /2/tweets/:id | ✅ | ✅ Scopes: tweet.read tweet.write users.read | |
Timelines User Tweet timeline GET /2/users/:id/tweets User mention timeline GET /2/users/:id/mentions Reverse chronological home timeline GET /2/users/:id/timelines/reverse_cronological | ✅ ✅ | ✅ | ✅ Scopes: tweet.read users.read ✅ Scopes: tweet.read users.read |
Recent search Search for Tweets published in the last 7 days GET /2/tweets/search/recent | ✅ | ✅ | ✅ Scopes: tweet.read users.read |
Full-archive search Only available to those with Academic Research access Search the full archive of Tweets GET /2/tweets/search/all | ✅ | ||
Filtered stream Add or delete rules from your stream POST /2/tweets/search/stream/rules Retrieve your stream’s rules GET /2/tweets/search/stream/rules Connect to the stream GET /2/tweets/search/stream | ✅ | ||
Volume streams Streams about 1% of all Tweets in real-time. GET /2/tweets/sample/stream | ✅ | ||
Manage Retweets Retweet a Tweet POST /2/users/:id/retweets Delete a Retweet DELETE /2/users/:id/retweets/:source_tweet_id | ✅ | ✅ Scopes: tweet.read tweet.write users.read | |
Retweets lookup Users who have Retweeted a Tweet GET /2/tweets/:id/retweeted_by | ✅ | ✅ | ✅ Scopes: tweet.read users.read |
Bookmarks lookup Get bookmarked Tweets GET /2/tweets/:id/bookmarks | ✅ Scopes: tweet.read users.read bookmark.read | ||
Manage Bookmarks Bookmark a Tweet POST /2/tweets/:id/bookmarks Remove a Bookmark of a Tweet DELETE /2/users/:id/bookmarks:tweet_id | ✅ Scopes: tweet.read users.read bookmark.write | ||
Manage Likes Like a Tweet POST /2/users/:id/likes Undo a Like of a Tweet DELETE /2/users/:id/likes/:tweet_id | ✅ | ✅ Scopes: tweet.read users.read like.write | |
Likes lookup Users who have liked a Tweet GET /2/tweets/:id/liking_users Tweets liked by a user GET /2/users/:id/liked_tweets | ✅ | ✅ | ✅ Scopes: tweet.read users.read like.read |
Hide replies Hides or unhides a reply to a Tweet. PUT /2/tweets/:id/hidden | ✅ | ✅ Scopes: tweet.read users.read tweet.moderate.write | |
Users lookup Retrieve multiple users with IDs GET /2/users Retrieve a single user with an ID GET /2/users/:id Retrieve multiple users with usernames GET /2/users/by Retrieve a single user with a usernames GET /2/users/by/username/:username Get information about an authenticated user GET /2/users/me | ✅ | ✅ | ✅ Scopes: tweet.read users.read |
Manage follows Allows a user ID to follow another user POST /2/users/:id/following Allows a user ID to unfollow another user DELETE /2/users/:source_user_id/following/:target_user_id | ✅ | ✅ Scopes: tweet.read users.read follows.write | |
Follows lookup Lookup following of a user by ID GET /2/users/:id/following Lookup followers of a user by ID GET /2/users/:id/followers | ✅ | ✅ | ✅ Scopes: tweet.read users.read follows.read |
Manage blocks Allows a user ID to block another user POST /2/users/:id/blocking Allows a user ID to unblock another user DELETE /2/users/:source_user_id/blocking/:target_user_id | ✅ | ✅ Scopes: tweet.read users.read block.write | |
Blocks lookup Returns a list of users who are blocked by the specified user ID GET /2/users/:id/blocking | ✅ | ✅ Scopes: tweet.read users.read block.read | |
Manage Mutes Allows a user ID to mute another user POST /2/users/:id/muting Allows a user ID to unmute another user DELETE /2/users/:source_user_id/muting/:target_user_id | ✅ | ✅ Scopes: tweet.read users.read mute.write | |
Mutes lookup Returns a list of users who are muted by the specified user ID GET /2/users/:id/muting | ✅ | ✅ Scopes: tweet.read users.read mute.read | |
Spaces lookup Lookup Space by ID GET /2/spaces/:id Lookup multiple Spaces GET /2/spaces Discover Spaces created by user ID GET /2/spaces/by/creator_ids | ✅ | ✅ Scopes: tweet.read users.read space.read | |
Spaces lookup Get users who purchased a ticket to a Space GET /2/spaces/:id/buyers | ✅ Scopes: tweet.read users.read space.read | ||
Spaces search Returns live or scheduled Spaces matching your specified search terms. GET /2/spaces/search | ✅ | ✅ Scopes: tweet.read users.read space.read | |
List lookup Lookup a specific list by ID GET /2/lists/:id Lookup a user’s owned List GET /2/users/:id/owned_lists | ✅ | ✅ | ✅ Scopes: tweet.read users.read list.read |
Manage Lists Creates a new List on behalf of an authenticated user POST /2/lists | ✅ | ✅ Scopes: tweet.read users.read list.read list.write | |
Manage Lists Deletes a List the authenticated user owns DELETE /2/lists/:id Updates the metadata for a List the authenticated user owns PUT /2/lists/:id | ✅ | ✅ Scopes: tweet.read users.read list.write | |
List Tweets lookup Lookup Tweets from a specified List GET /2/lists/:id/tweets | ✅ | ✅ | ✅ Scopes: tweet.read users.read list.read |
List members lookup Returns a list of members from a specified List GET /2/lists/:id/members Returns all Lists a specified user is a member of GET /2/users/:id/list_memberships | ✅ | ✅ | ✅ Scopes: tweet.read users.read list.read |
Manage List members Add a member to a List that the authenticated user owns POST /2/lists/:id/members Removes a member from a List the authenticated user owns DELETE /2/lists/:id/members/:user_id | ✅ | ✅ Scopes: tweet.read users.read list.write | |
List follows lookup Returns all followers of a specified List GET /2/lists/:id/followers Returns all Lists a specified user follows GET /2/users/:id/followed_lists | ✅ | ✅ | ✅ Scopes: tweet.read users.read list.read |
Manage List follows Follows a List on behalf of an authenticated user POST /2/users/:id/followed_lists Unfollows a List on behalf of an authenticated user DELETE /2/users/:id/followed_lists/:list_id | ✅ | ✅ Scopes: tweet.read users.read list.write | |
Pinned List lookup Returns the pinned Lists of the authenticated user GET /2/users/:id/pinned_lists | ✅ | ✅ Scopes: tweet.read users.read list.read | |
Manage pinned List Pins a List on behalf of an authenticated user POST /2/users/:id/pinned_lists Unpins a List on behalf of an authenticated user DELETE /2/users/:id/pinned_lists/:list_id | ✅ | ✅ Scopes: tweet.read users.read list.write | |
Batch compliance Creates a new compliance job POST /2/compliance/jobs Returns status and download information about a specified compliance job GET /2/compliance/jobs/:job_id Returns a list of recent compliance jobs GET /2/compliance/jobs | ✅ |
OAuth 1.0a
Many endpoints on the Twitter developer platform use the OAuth 1.0a method to act, or make API requests, on behalf of a Twitter account. For example, if you have a Twitter developer app, you can make API requests on behalf of any Twitter account as long as that user authenticates your app.
Please note: if you aren’t familiar with concepts such as HMAC-SHA1 and percent encoding, we recommend that you check out the “useful tools” section below that lists some API clients that greatly simplify the authentication process.
Key concepts
Signing a request with keys and tokens
You have to sign each API request by passing several generated keys and tokens in an authorization header. To start, you can generate several keys and tokens in your [Twitter developer app’s]/resources/fundamentals/developer-apps) details page, including the following:
API key and secret:oauth_consumer_key oauth_consumer_secret | Think of these as the user name and password that represents your Twitter developer app when making API requests. |
Access token and secret:oauth_token oauth_token_secret | An access token and access token secret are user-specific credentials used to authenticate OAuth 1.0a API requests. They specify the Twitter account the request is made on behalf of. You can generate your own access token and token secret if you would like your app to make requests on behalf of the same Twitter account associated with your developer account on the [Twitter developer app’s]/resources/fundamentals/developer-apps) details page. If you’d like to generate access tokens for a different user, see “Making requests on behalf of users” below. |
Making requests on behalf of users
When creating a signature, you need a set of access tokens that represent the user that you are going to make a request on behalf of.
You can generate a set of access tokens that represents the Twitter account that owns the Twitter developer app from the app’s details page, but if you are wanting to make a request on behalf of a different Twitter account, that account’s owner must grant access to you by signing in to their account as part of the 3-legged OAuth flow. The output of this process is a set of access tokens (oauth_token and oauth_token_secret) that can be used to make a OAuth 1.0a request.
Once you have these keys and tokens, you can either create a signature from scratch. We don’t recommended this unless you know what you are doing, or if you’re using one of the tools mentioned below to make a request to an endpoint that requires OAuth 1.0a.
For reference, here is an example of a signed cURL request with all of the generated tokens passed in an authorization header:
`curl —request POST \
—url ‘https://api.x.com/1.1/statuses/update.json?status=Hello%20world’ \
—header ‘authorization: OAuth oauth_consumer_key=“CONSUMER_API_KEY”, oauth_nonce=“OAUTH_NONCE”, oauth_signature=“OAUTH_SIGNATURE”, oauth_signature_method=“HMAC-SHA1”, oauth_timestamp=“OAUTH_TIMESTAMP”, oauth_token=“ACCESS_TOKEN”, oauth_version=“1.0”’ `
Code copied to clipboard
Please note that user access tokens are sensitive and should be guarded very carefully. When access tokens are generated, the user they represent is trusting your application to keep them secure. If the security of both API keys and user access tokens are compromised, your application would potentially expose access to private information and account functionality. We encourage you to learn more about securing keys and access tokens.
Useful tools
The process of signing a request is complicated. We recommend that you use an API client library that automatically generates a lot of the authentication token:
Postman | An API client that lets you build and send REST API requests. Read our “Getting started with Postman” tutorial to learn more about this tool. |
Insomnia | Insomnia is a REST API Client with cookie management, environment variables, code generation, and authentication for Mac, Window, and Linux. |
Learn more
Guides
API Key and Secret
The API Key and Secret (also known as Consumer Key and Secret) are the most fundamental credentials required to access the Twitter API. These credentials act as the username and password for your Twitter App, and are used by the Twitter API to understand which App requests are coming from.
These credentials can be used by authentication endpoints to generate additional credentials, such as user Access Tokens and Secrets, and Bearer Tokens. You also need to use these credentials along with Access Tokens and other authorization parameters to authorize requests that require OAuth 1.0a User Context authentication.
How to acquire an API Key and Secret
To acquire a Twitter API Key and Secret, please follow these steps:
- Sign up for a Twitter developer account
- Create a Twitter App within the developer portal. Note that if you would like to use Twitter API v2, you must add your Twitter App to a Project.
When you create your Twitter App, you will be presented with your API Key and Secret, along with a Bearer Token. Please note that we only display these credentials once, so make sure to save them in your password manager or somewhere secure.
We have more recommendations on how to handle your keys and tokens within our authentication best practices page, including details on what you should do if your credentials have been compromised.
How to find and regenerate your API Key and Secret after App creation
If you’ve already created an App and need to find or regenerate your API Key and Secret, please follow these steps:
- Navigate to the developer portal
- Expand the ‘Projects and Apps’ dropdown in the sidenav
- Open the App which is associated with the API Key and Secret that you would like to find or regenerate
- Navigate to the Keys and tokens tab
From there, you will find all of the credentials associated with your App.
How to use your API Key and Secret
If you are just exploring the Twitter Developer Platform, we recommend that you use a tool or library to see what’s available on the platform. These tools handle authentication gracefully, and can save you a lot of time and frustration. We specifically recommend getting started with Postman or Insomnia for beginner developers.
If you are interested in building a request from scratch, please read our guide on authorizing an OAuth 1.0a request.
Next step
Learn more about user Access Tokens
Make your first request using your API Key and Secret
Obtaining Access Tokens using 3-legged OAuth flow
To perform actions on behalf of another user, you’ll need to obtain their access tokens. Access tokens specify the Twitter account the request is made on behalf of, so for you to obtain these they will need to first grant you access. These tokens do not expire but can be revoked by the user at any time.
Twitter allows you to obtain user access tokens through the 3-legged OAuth flow, which allows your application to obtain an access token and access token secret by redirecting a user to Twitter and having them authorize your application. This flow is almost identical to the flow described in implementing Log in with Twitter, with two exceptions:
- The GET oauth/authorize endpoint is used instead of GET oauth/authenticate.
- The user will always be prompted to authorize access to your application, even if access was previously granted.
Before you get started, you will need to check your application’spermissions and know the consumer keys and callback URL. If you don’t have a callback URL or publicly accessible UI, consider using PIN-based authorization, which is intended for applications that cannot access or embed a web browser in order to redirect the user after authorization.
The possible states for the 3-legged sign in interaction are illustrated in the following flowchart:
Overview of the process
At a high level, the 3-Legged OAuth process will:
- Create a request for a consumer application to obtain a request token.
- Have the user authenticate, and send the consumer application a request token.
- Convert the request token into a usable user access token.
Terminology clarification
In the guide below, you may see different terms referring to the same thing.
Client credentials:
- App Key === API Key === Consumer API Key === Consumer Key === Customer Key ===
oauth_consumer_key
- App Key Secret === API Secret Key === Consumer Secret === Consumer Key === Customer Key ===
oauth_consumer_secret
- Callback URL ===
oauth_callback
Temporary credentials:
- Request Token ===
oauth_token
- Request Token Secret ===
oauth_token_secret
- oauth_verifier
Token credentials:
- Access token === Token === resulting
oauth_token
- Access token secret === Token Secret === resulting
oauth_token_secret
Walkthrough steps
Step 1: POST oauth/request_token
Create a request for a consumer application to obtain a request token.
The only unique parameter in this request is oauth_callback, which must be a URL encoded version of the URL you wish your user to be redirected to when they complete step 2. The remaining parameters are added by the OAuth signing process.
Please note - any callback URL that you use with the POST oauth/request_token endpoint will have to be configured within your developer App’s settings in the app details page of developer portal.
Request includes:
oauth_callback="https%3A%2F%2FyourCallbackUrl.com"
oauth_consumer_key="cChZNFj6T5R0TigYB9yd1w"
Your app should examine the HTTP status of the response. Any value other than 200 indicates a failure. The body of the response will contain the oauth_token
, oauth_token_secret
, and oauth_callback_confirmed
parameters. Your app should verify that oauth_callback_confirmed
is true and store the other two values for the next steps.
Response includes
oauth_token=NPcudxy0yU5T3tBzho7iCotZ3cnetKwcTIRlX0iwRl0
oauth_token_secret=veNRnAWe6inFuo8o2u8SLLZLjolYDmDP7SzL0YfYI
oauth_callback_confirmed=true
Step 2: GET oauth/authorize
Have the user authenticate, and send the consumer application a request token.
Example URL to redirect user to:
https://api.x.com/oauth/authorize?oauth_token=NPcudxy0yU5T3tBzho7iCotZ3cnetKwcTIRlX0iwRl0
Upon successful authentication, your callback_url
would receive a request containing the oauth_token
and oauth_verifier
parameters. Your application should verify that the token matches the request token received in step 1.
Request from client’s redirect:
https://yourCallbackUrl.com?oauth_token=NPcudxy0yU5T3tBzho7iCotZ3cnetKwcTIRlX0iwRl0&oauth_verifier=uw7NjWHT6OJ1MpJOXsHfNxoAhPKpgI8BlYDhxEjIBY
Step 3: POST oauth/access_token
Convert the request token into a usable access token.
To render the request token into a usable access token, your application must make a request to the POST oauth/access_token endpoint, containing the oauth_verifier
value obtained in step 2. The request token is also passed in the oauth_token
portion of the header, but this will have been added by the signing process.
Request includes:
POST /oauth/access_token
oauth_consumer_key=cChZNFj6T5R0TigYB9yd1w
oauth_token=NPcudxy0yU5T3tBzho7iCotZ3cnetKwcTIRlX0iwRl0
oauth_verifier=uw7NjWHT6OJ1MpJOXsHfNxoAhPKpgI8BlYDhxEjIBY
A successful response contains the oauth_token
, oauth_token_secret
parameters. The token and token secret should be stored and used for future authenticated requests to the Twitter API. To determine the identity of the user, use GET account/verify_credentials.
Response includes:
oauth_token=7588892-kagSNqWge8gB1WwE3plnFsJHAZVfxWD7Vb57p0b4
oauth_token_secret=PbKfYqSryyeKDWz4ebtY3o5ogNLG11WJuZBc9fQrQo
Using these credentials for OAuth 1.0a (application-user) required requests
Now you’ve obtained the user access tokens; you can use them to access certain APIs such as POST statuses/update to create Tweets on the users’ behalf.
Request includes:
POST statuses/update.json
oauth_consumer_key=cChZNFj6T5R0TigYB9yd1w
oauth_token=7588892-kagSNqWge8gB1WwE3plnFsJHAZVfxWD7Vb57p0b4
Sample use case
The standard flow is web-based and uses the 3-legged authorization OAuth flow. The screenshots outlined here are part of a sample that you can view the source of at https://github.com/twitterdev/twauth-web.
At some point in your application, you will want to redirect to Twitter in order to authorize your application.
When you redirect to Twitter with the request token, the user will be prompted to authorize your application.
Upon authorizing your application, the user will be redirected to the callback URL provided when you generated the request token. You will use this to obtain the permanent access token for this user and store it locally.
Authorizing a request
The purpose of this document is to show you how to modify HTTP requests for the purpose of sending authorized requests to the Twitter API.
All of Twitter’s APIs are based on the HTTP protocol. This means that any software you write which uses Twitter’s APIs sends a series of structured messages to Twitter’s servers. For example, a request to post the text “Hello Ladies + Gentlemen, a signed OAuth request!” as a Tweet will look something like this:
Any HTTP library should be able to generate and issue the above request with a minimum of difficulty. However, the above request is considered invalid, since there is no way of knowing:
- Which application is making the request
- Which user the request is posting on behalf of
- Whether the user has granted the application authorization to post on the user’s behalf
- Whether the request has been tampered by a third party while in transit
To allow applications to provide this information, Twitter’s API relies on the OAuth 1.0a protocol. At a very simplified level, Twitter’s implementation requires that requests needing authorization contain an additional HTTP Authorization header with enough information to answer the questions listed above. A version of the HTTP request shown above, modified to include this header, looks like this (normally the Authorization header would need to be on one line, but has been wrapped for legibility here):
When this request was created, it would have been accepted by the Twitter API as valid.
If this signing process sounds like it is beyond the scope of your integration, consider using Web Intents, which do not need to use OAuth to interact with the Twitter API.
Collecting parameters
You should be able to see that the header contains 7 key/value pairs, where the keys all begin with the string “oauth_”. For any given Twitter API request, collecting these 7 values and creating a similar header will allow you to specify authorization for the request. How each value was generated is described below:
Consumer key
The oauth_consumer_key identifies which application is making the request. Obtain this value from the settings page for your Twitter app in the developer portal.
oauth_consumer_key | xvz1evFS4wEEPTGEFPHBog |
Nonce
The oauth_nonce parameter is a unique token your application should generate for each unique request. Twitter will use this value to determine whether a request has been submitted multiple times. The value for this request was generated by base64 encoding 32 bytes of random data, and stripping out all non-word characters, but any approach which produces a relatively random alphanumeric string should be OK here.
oauth_nonce | kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg |
Signature
The oauth_signature parameter contains a value which is generated by running all of the other request parameters and two secret values through a signing algorithm. The purpose of the signature is so that Twitter can verify that the request has not been modified in transit, verify the application sending the request, and verify that the application has authorization to interact with the user’s account.
The process for calculating the oauth_signature for this request is described in Creating a signature.
oauth_signature | tnnArxj06cWHq44gCs1OSKk/jLY= |
Signature method
The oauth_signature_method used by Twitter is HMAC-SHA1. This value should be used for any authorized request sent to Twitter’s API.
oauth_signature_method | HMAC-SHA1 |
Timestamp
The oauth_timestamp parameter indicates when the request was created. This value should be the number of seconds since the Unix epoch at the point the request is generated, and should be easily generated in most programming languages. Twitter will reject requests which were created too far in the past, so it is important to keep the clock of the computer generating requests in sync with NTP.
oauth_timestamp | 1318622958 |
Token
The oauth_token parameter typically represents a user’s permission to share access to their account with your application. There are a few authentication requests where this value is not passed or is a different form of token, but those are covered in detail in Obtaining access tokens. For most general-purpose requests, you will use what is referred to as an access token.
You can generate a valid access token for your account on the settings page for your Twitter app on the developer portal.
oauth_token | 370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb |
Version
The oauth_version parameter should always be 1.0 for any request sent to the Twitter API.
oauth_version | 1.0 |
Building the header string
To build the header string, imagine writing to a string named DST.
- Append the string “OAuth ” (including the space at the end) to DST.
- For each key/value pair of the 7 parameters listed above:
- Percent encode the key and append it to DST.
- Append the equals character ‘=’ to DST.
- Append a double quote ‘”’ to DST.
- Percent encode the value and append it to DST.
- Append a double quote ‘”’ to DST.
- If there are key/value pairs remaining, append a comma ‘,’ and a space ‘ ‘ to DST.
Pay particular attention to the percent encoding of the values when building this string. For example, the oauth_signature value of tnnArxj06cWHq44gCs1OSKk/jLY= must be encoded as tnnArxj06cWHq44gCs1OSKk%2FjLY%3D.
Performing these steps on the parameters collected above results in the following string:
OAuth oauth_consumer_key=“xvz1evFS4wEEPTGEFPHBog”, oauth_nonce=“kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg”, oauth_signature=“tnnArxj06cWHq44gCs1OSKk%2FjLY%3D”, oauth_signature_method=“HMAC-SHA1”, oauth_timestamp=“1318622958”, oauth_token=“370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb”, oauth_version=“1.0”
This value should be set as the Authorization header for the request.
OAuth Echo
OAuth Echo is a means to securely delegate OAuth authorization with a third party while interacting with an API.
There are four parties involved in this interaction:
- the User who is using Twitter through a particular, authorized Twitter application
- the Consumer, or the Twitter application that is attempting to interact with the 3rd party media provider (e.g. the photo-sharing site)
- the Delegator, or the 3rd party media provider
- the Service Provider a.k.a. Twitter itself
Essentially, prepare a request for the delegator to send to the Twitter API on behalf of an application and a user. Add what would otherwise be a signed OAuth request into an HTTP header and ask the delegator to send that request to Twitter after completing the intermediary operation.
Here’s an example: the User wants to upload a photo. The Consumer is going to call upload on the Delegator with a POST. The POST should contain the image, but it should also contain two additional items as HTTP headers:
- x-auth-service-provider — effectively, this is the realm that identity delegation should be sent to — in the case of Twitter, set this to https://api.x.com/1.1/account/verify_credentials.json. iOS5-based Twitter integrations will add an additional application_id parameter to this URL that will also be used to calculate the oauth_signature used in x-verify-credentials-authorization.
- x-verify-credentials-authorization — Consumer should create all the OAuth parameters necessary so it could call https://api.x.com/1.1/account/verify_credentials.json using OAuth in the HTTP header (e.g. it should look like OAuth oauth_consumer_key=”…”, oauth_token=”…”, oauth_signature_method=”…”, oauth_signature=”…”, oauth_timestamp=”…”, oauth_nonce=”…”, oauth_version=”…” ).
Keep in mind that the entire transaction period needs to occur within an amount of time where the oauth_timestamp will still be valid.
Alternatively, instead of sending these two parameters in the header, they could be sent in the POST as x_auth_service_provider and x_verify_credentials_authorization — in this case, remember to escape and include the parameters in the OAuth signature base string — similar to encoding parameters in any request. It’s best to use HTTP headers to keep the operations as separate as possible.
The Delegators goal, at this point, is to verify that the User is who they say they are before it saves the media. Once the Delegator receives all the data above via its upload method, it should temporarily store the image, and then construct a call to the endpoint specified in the x-auth-service-provider header — in this case, https://api.x.com/1.1/account/verify_credentials.json, using the same OAuth authentication header provided by the Consumer in the x-verify-credentials-authorization header.
OAuth Echo best practices
Use the URL provided by x-auth-service-provider to perform the lookup, not a hard-coded value. Apple iOS, for example, adds an additional application_id parameter to all OAuth requests, and its existence should be maintained at each stage of OAuth Echo.
For the OAuth authorization portion, take the header value in x-verify-credentials-authorization, and place that into its own Authorization header for its call to the service provider. For good measure, confirm that the value in x-auth-service-provider is what it should be.
- If the Service Provider returns an HTTP 200, then good. The Delegator should permanently store the image, generate a URL, and return it.
- If the Service Provider doesn’t return an HTTP 200, then dump the image, and then return an error back to the Consumer.
PIN-based authorization
The PIN-based OAuth flow is a version of the 3-legged OAuth process and is intended for applications that cannot access or embed a web browser to redirect the user after authorization. Examples of such applications would be command-line applications, embedded systems, game consoles, and certain types of mobile apps.
PIN-based OAuth flow is initiated by an app in the request_token
with the oauth_callback
set to oob
. The term oob
means out-of-band OAuth. The user still visits Twitter to login or authorize the app, but they will not be automatically redirected to the application upon approving access. Instead, they will see a numerical PIN code, with instructions to return to the application and enter this value.
Please note: The callback_url
within the Twitter app settings is still required, even when using PIN-based auth.
Implementing the PIN-based OAuth flow
The PIN-based flow is implemented in the same way as 3-legged authorization (and Sign in with Twitter), with the following differences:
-
The value for
oauth_callback
must be set tooob
during the POST oauth/request_token call. -
After the user is sent to Twitter to authorize your app using either a GET oauth/authenticate or GET oauth/authorize URL, they will not be redirected to your
callback_url
, instead they will see a screen with a Twitter generated ~7 digit PIN with directions to enter the PIN into your applications name. -
The user enters this PIN into your application, and your application uses the PIN number as the
oauth_verifier
in the POST oauth/access_token to obtain an access_token.
Please note: PIN numbers are not reusable, and the access_token
obtained should be used for application-user requests.
Creating a signature
This page explains how to generate an OAuth 1.0a HMAC-SHA1 signature for an HTTP request. This signature will be suitable for passing to the Twitter API as part of an authorized request, as described in authorizing a request.
The request used to demonstrate signing is a POST to https://api.x.com/1.1/statuses/update.json. The raw request looks like this:
Collecting the request method and URL
To produce a signature, start by determining the HTTP method and URL of the request. These two are known when creating the request, so they are easy to obtain.
The request method will almost always be GET or POST for Twitter API requests.
HTTP Method | POST |
The base URL is the URL to which the request is directed, minus any query string or hash parameters. It is important to use the correct protocol here, so make sure that the “https://” portion of the URL matches the actual request sent to the API.
Base URL | https://api.x.com/1.1/statuses/update.json |
Collecting parameters
Next, gather all of the parameters included in the request. There are two such locations for these additional parameters - the URL (as part of the query string) and the request body. The sample request includes a single parameter in both locations:
An HTTP request has parameters that are URL encoded, but you should collect the raw values. In addition to the request parameters, every oauth_* parameter needs to be included in the signature, so collect those too. Here are the parameters from authorizing a request:
status | Hello Ladies + Gentlemen, a signed OAuth request! |
include_entities | true |
oauth_consumer_key | xvz1evFS4wEEPTGEFPHBog |
oauth_nonce | kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg |
oauth_signature_method | HMAC-SHA1 |
oauth_timestamp | 1318622958 |
oauth_token | 370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb |
oauth_version | 1.0 |
These values need to be encoded into a single string, which will be used later on. The process to build the string is very specific:
- Percent encode every key and value that will be signed.
- Sort the list of parameters alphabetically [1] by encoded key [2].
- For each key/value pair:
- Append the encoded key to the output string.
- Append the ‘=’ character to the output string.
- Append the encoded value to the output string.
- If there are more key/value pairs remaining, append a ‘&’ character to the output string.
[1] The OAuth spec says to sort lexicographically, which is the default alphabetical sort for many libraries.
[2] In the case of two parameters with the same encoded key, the OAuth spec says to continue sorting based on value. However, Twitter does not accept duplicate keys in API requests
Parameter string
The following parameter string will be produced by repeating these steps with the parameters collected above:
include_entities=true&oauth_consumer_key=xvz1evFS4wEEPTGEFPHBog&oauth_nonce=kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1318622958&oauth_token=370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb&oauth_version=1.0&status=Hello%20Ladies%20%2B%20Gentlemen%2C%20a%20signed%20OAuth%20request%21
Creating the signature base string
The three values collected so far must be joined to make a single string, from which the signature will be generated. This is called the signature base string by the OAuth specification.
To encode the HTTP method, base URL, and parameter string into a single string:
- Convert the HTTP Method to uppercase and set the output string equal to this value.
- Append the ‘&’ character to the output string.
- Percent encode the URL and append it to the output string.
- Append the ‘&’ character to the output string.
- Percent encode the parameter string and append it to the output string.
This will produce the following signature base string:
Make sure to percent encode the parameter string. The signature base string should contain exactly 2 ampersand ‘&’ characters. The percent ‘%’ characters in the parameter string should be encoded as %25 in the signature base string.
Getting a signing key
The last pieces of data to collect are secrets which identify the Twitter app making the request, and the user the request is on behalf of. It is very important to note that these values are incredibly sensitive and should never be shared with anyone.
The value which identifies your app to Twitter is called the consumer secret and can be found in the developer portal by viewing the app details page. This will be the same for every request your Twitter app sends.
Consumer secret | kAcSOqF21Fu85e7zjz7ZN2U4ZRhfV3WpwPAoE3Z7kBw |
The value which identifies the account your application is acting on behalf of is called the OAuth token secret. This value can be obtained in several ways, all of which are described in obtaining access tokens.
OAuth token secret | LswwdoUaIvS8ltyTt5jkRh4J50vUPVVHtR2YPi5kE |
Once again, it is very important to keep these values private to your application. If you feel that your values have been compromised, regenerate your tokens (the tokens on this page have been marked as invalid for real requests).
Both of these values need to be combined to form a signing key which will be used to generate the signature. The signing key is simply the percent encoded consumer secret, followed by an ampersand character ‘&’, followed by the percent encoded token secret:
Note that there are some flows, such as when obtaining a request token, where the token secret is not yet known. In this case, the signing key should consist of the percent encoded consumer secret followed by an ampersand character ‘&’.
Signing key | kAcSOqF21Fu85e7zjz7ZN2U4ZRhfV3WpwPAoE3Z7kBw&LswwdoUaIvS8ltyTt5jkRh4J50vUPVVHtR2YPi5kE |
Calculating the signature
Finally, the signature is calculated by passing the signature base string and signing key to the HMAC-SHA1 hashing algorithm. The details of the algorithm are explained as hash_hmac function.
The output of the HMAC signing function is a binary string. This needs to be base64 encoded to produce the signature string. For example, the output given the base string and signing key given on this page is 2E CF 77 84 98 99 6D 0D DA 90 5D C7 17 7C 75 07 3F 3F CD 4E. That value, when converted to base64, is the OAuth signature for this request:
OAuth signature | Ls93hJiZbQ3akF3HF3x1Bz8/zU4= |
Percent encoding parameters
Parts of the Twitter API, particularly those dealing with OAuth signatures, require strings to be encoded according to RFC 3986, Section 2.1. Since many implementations of URL encoding algorithms are not fully compatible with RFC 3986, bad encodings are a cause of many OAuth signature errors. For this reason, the exact signing algorithm to use is covered on this page.
This page covers the URL encoding process described in RFC 3986, Section 2.1. We encourage you to reference that specification in case of any ambiguity or conflict with this document.
Encoding a string
The following algorithm assumes you are encoding a string SRC by copying its values byte-by-byte to a string DST.
Step 1: While SRC contains unread bytes, read the next byte (8 bits) from SRC. Typically, this is considered a character, but in the case of encodings where a character may be more than one byte (such as UTF-8), just read the first byte.
Step 2: Check whether the read byte matches any of the following ASCII equivalents. The following table has been broken down into rows for legibility, but you only need to determine whether the read byte exists in the table at all, not the specific row.
Name | ASCII characters | Equivalent byte values |
---|---|---|
Digits | ‘0’, ‘1’, ‘2’, ‘3’, ‘4’, ‘5’, ‘6’, ‘7’, ‘8’, ‘9’ | 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39 |
Uppercase letters | ‘A’, ‘B’, ‘C’, ‘D’, ‘E’, ‘F’, ‘G’, ‘H’, ‘I’, ‘J’, ‘K’, ‘L’, ‘M’, ‘N’, ‘O’, ‘P’, ‘Q’, ‘R’, ‘S’, ‘T’, ‘U’, ‘V’, ‘W’, ‘X’, ‘Y’, ‘Z’ | 0x41, 0x42, 0x43, 0x44, 0x45,0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B,0x4C, 0x4D, 0x4E, 0x4F, 0x50, 0x51,0x52, 0x53, 0x54, 0x55, 0x56, 0x57,0x58, 0x59, 0x5A |
Lowercase letters | ‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’, ‘g’, ‘h’, ‘i’, ‘j’, ‘k’, ‘l’, ‘m’, ‘n’, ‘o’, ‘p’, ‘q’, ‘r’, ‘s’, ‘t’, ‘u’, ‘v’, ‘w’, ‘x’, ‘y’, ‘z’ | 0x61, 0x62, 0x63, 0x64, 0x65,0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B,0x6C, 0x6D, 0x6E, 0x6F, 0x70, 0x71,0x72, 0x73, 0x74, 0x75, 0x76, 0x77,0x78, 0x79, 0x7A |
Reserved characters | ‘-‘, ‘.’, ‘_’, ‘~’ | 0x2D, 0x2E, 0x5F, 0x7E |
Step 2b: If the byte is not listed in the above table, continue. Any other value must be encoded. Step 2a: If the byte is listed in the above table, copy it into DST and go back to Step 1. Characters listed in the above table do not need to be escaped, so you will just copy the byte directly.
Step 3: Write the character ‘%’ to DST. The percent character ‘%’ (or 0x25 in hex and 00100101 in binary) indicates that the next two bytes will represent an encoded byte.
**Step 4: Write two characters representing the uppercase ASCII-encoded hex value of the current byte to DST. **This is a bit confusing, so here is an example. Pretend the current byte is 0xE6 (11100110 in binary). This corresponds with the UTF-8 encoded value of ‘æ’. To encode this value, write the character ‘E’ (0x45, from the table above) and then the character ‘6’ (0x36) to DST. The last three characters are written should have been “%E6”. Note that if you write a letter such as A,B,C,D,E or F, you must use the uppercase character.
Step 5: Return to Step 1. Keep going until the entirety of SRC is copied to DST.
Examples
The following examples may be helpful to compare with the output of your own code. You should consider any differences an error. Spaces encoded as “+” characters are an example of incorrect encoding.
Original string | Encoded string |
---|---|
Ladies + Gentlemen | Ladies%20%2B%20Gentlemen |
An encoded string! | An%20encoded%20string%21 |
Dogs, Cats & Mice | Dogs%2C%20Cats%20%26%20Mice |
☃ | %E2%98%83 |
OAuth 2.0
Bearer Token (also known as app-only)
OAuth 2.0 Bearer Token authenticates requests on behalf of your developer App. As this method is specific to the App, it does not involve any users. This method is typically for developers that need read-only access to public information.
This authentication method requires for you to pass a Bearer Token with your request, which you can generate within the Keys and tokens section of your developer Apps. Here is an example of what a request looks like with a fake Bearer Token:
API calls using app-only authentication are rate limited per endpoint at the App level.
To use this method, you’ll need a Bearer Token, which you can generate by passing your API Key and Secret through the POST oauth2/token endpoint, or by generating it in the “keys and token” section of your App settings in the [developer portal]/resources/fundamentals/developer-portal).
If you’d like to revoke a Bearer Token, you can use the POST oauth2/invalidate_token endpoint, or click where it says “revoke” next to the Bearer Token in the “keys and tokens” section of your App settings.
OAuth 2.0 Authorization Code Flow with PKCE
OAuth 2.0 Authorization Code Flow with PKCE allows you to authenticate on behalf of another user with have more control over an application’s scopes and improves authorization flows across multiple devices. In other words, developers building applications for people on Twitter will have more control over the information their App requests from its users, so that you only have to ask your end-users for the data and information you need.
This modern authorization protocol will allow you to present your end-users with a more streamlined consent flow for authorizing your app, which only displays the specific scopes you have requested from them. Not only does this reduce your data burden, but it may also lead to increased trust from end-users.
App only authentication and OAuth 2.0 Bearer Token
Twitter offers applications the ability to issue authenticated requests on behalf of the application itself, as opposed to on behalf of a specific user. Twitter’s implementation is based on the Client Credentials Grant flow of the OAuth 2 specification.
Application-only authentication doesn’t include any user-context and is a form of authentication where an application makes API requests on its own behalf. This method is for developers that just need read-only access to public information.
You can do application-only authentication using your apps consumer API keys, or by using a App only Access Token (Bearer Token). This means that the only requests you can make to a Twitter API must not require an authenticated user.
With application-only authentication, you can perform actions such as:
- Pull user timelines
- Access friends and followers of any account
- Access lists resources
- Search Tweets
Please note that only OAuth 1.0a or OAuth 2.0 Authorization Code Flow with PKCE is required to issues requests on behalf of users. The API reference page describes the authentication method required to use an API. You will need user-authentication, user-context, with an access token to perform the following:
- Post Tweets or other resources
- Search for users
- Use any geo endpoint
- Access Direct Messages or account credentials
- Retrieve user’s email addresses
Auth Flow
To use this method, you need to use a App only Access Token(also known as Bearer Token). You can generate an App only Access Token (Bearer Token) by passing your consumer key and secret through the POST oauth2/token endpoint.
The application-only auth flow follows these steps:
- An application encodes its consumer key and secret into a specially encoded set of credentials.
- An application makes a request to the POST oauth2/token endpoint to exchange these credentials for an App only Access Token.
- When accessing the REST API, the application uses the App only Access Token to authenticate.
Because there is no need to sign a request, this approach is much simpler than the standard OAuth 1.0a model.
About application-only auth
Tokens are passwords
Keep in mind that the consumer key & secret and the App only Access Token (Bearer Token) itself grant access to make requests on behalf of an application. These values should be considered as sensitive as passwords, and must not be shared or distributed to untrusted parties.
SSL required
All requests (both to obtain and use the tokens) must use HTTPS endpoints. Follow the best practices detailed in Connecting to Twitter API using TLS — peers should always be verified.
No user-context
When issuing requests using application-only auth, there is no concept of a “current user”. Therefore, endpoints such as POST statuses/update will not function with application-only auth. See using OAuth for more information for issuing requests on behalf of a user.
Rate limiting
Applications have two kinds of rate limiting pools.
Requests made on behalf of users with access tokens, also known as user-context, depletes from a different rate limiting context than that used in application-only authentication. So, in other words, requests made on behalf of users will not deplete from the rate limits available through app-only auth, and requests made through app-only auth will not deplete from the rate limits used in user-based auth.
You can view the rate limit by using the GET application/rate_limit_status endpoint, which supports application-only authentication. By issuing requests to this method with your application Bearer Token, you’ll receive a response indicating the current window’s per-resource rate limiting context. Instead of receiving a “rate_limit_context” field indicating the access token being used, you will receive a “application” field instead, with the value being your application’s consumer key.
Read more about API Rate Limiting and review the limits.
Issuing application-only requests
Step 1: Encode consumer key and secret
The steps to encode an application’s consumer key and secret into a set of credentials to obtain a Bearer Token are:
- URL encode the consumer key and consumer secret according to RFC 1738. Note that at the time of writing, this will not actually change the consumer key and secret, but this step should still be performed in case the format of those values changes in the future.
- Concatenate the encoded consumer key, a colon character ”:”, and the encoded consumer secret into a single string.
- Base64 encode the string from the previous step.
Below are example values showing the result of this algorithm. Note that the consumer secret used in this page is for test purposes and will not work for real requests.
Consumer key | xvz1evFS4wEEPTGEFPHBog |
Consumer secret | L8qq9PZyRg6ieKGEKhZolGC0vJWLw8iEJ88DRdyOg |
RFC 1738 encoded consumer key (does not change) | xvz1evFS4wEEPTGEFPHBog |
RFC 1738 encoded consumer secret (does not change) | L8qq9PZyRg6ieKGEKhZolGC0vJWLw8iEJ88DRdyOg |
Bearer Token credentials | xvz1evFS4wEEPTGEFPHBog:L8qq9PZyRg6ieKGEKhZolGC0vJWLw8iEJ88DRdyOg |
Base64 encoded Bearer Token credentials | :: eHZ6MWV2RlM0d0VFUFRHRUZQSEJvZzpMOHFxOVBaeVJnNmllS0dFS2hab2xHQzB2SldMdzhpRUo4OERSZHlPZw== |
Step 2: Obtain an App only Access Token (Bearer Token)
The value calculated in step 1 must be exchanged for an App only Access Token by issuing a request to POST oauth2/token:
- The request must be an HTTP POST request.
- The request must include an
Authorization
header with the value ofBasic <base64 encoded value from step 1>.
- The request must include a
Content-Type
header with the value ofapplication/x-www-form-urlencoded;charset=UTF-8.
- The body of the request must be
grant_type=client_credentials
.
Example request (Authorization header has been wrapped):
POST /oauth2/token HTTP/1.1 Host: api.x.com User-Agent: My Twitter App v1.0.23 Authorization: Basic eHZ6MWV2RlM0d0VFUFRHRUZQSEJvZzpMOHFxOVBaeVJn NmllS0dFS2hab2xHQzB2SldMdzhpRUo4OERSZHlPZw== Content-Type: application/x-www-form-urlencoded;charset=UTF-8 Content-Length: 29 Accept-Encoding: gzip
grant_type=client_credentials
If the request was formatted correctly, the server would respond with a JSON-encoded payload:
Example response:
Applications should verify that the value associated with the token_type
key of the returned object is bearer
. The value associated with the access_token
key is the App only Access Token (Bearer Token).
Note that one App only Access Token is valid for an application at a time. Issuing another request with the same credentials to /oauth2/token
will return the same token until it is invalidated.
Step 3: Authenticate API requests with the App only Access Token (Bearer Token)
The App only Access Token (Bearer Token) may be used to issue requests to API endpoints that support application-only auth. To use the App Access Token, construct a normal HTTPS request and include an Authorization
header with the value of Bearer <base64 bearer token value from step 2>. Signing is not required.
Example request (Authorization header has been wrapped):
Invalidating an App only Access Token (Bearer Token)
Should a App only Access Token become compromised or need to be invalidated for any reason, issue a call to POST oauth2/invalidate_token.
Example request (Authorization header has been wrapped):
Common error cases
This section describes some common mistakes involved in the negotiation and use of Bearer Tokens. Be aware that not all possible error responses are covered here - be observant of unhandled error codes and responses.
Invalid requests to obtain or revoke an App only Access Token
Attempts to:
- Obtain a App only Access Token (Bearer Token) with an invalid request (for example, leaving out
grant_type=client_credentials
). - Obtain or revoke an App only Access Token (Bearer Token) with incorrect or expired app credentials.
- Invalidate an incorrect or revoked App only Access Token (Bearer Token).
- Obtain an App only Access Token (Bearer Token) too frequently in a short period of time.
Will result in:
API request contains invalid App only Access Token (Bearer Token)
Using an incorrect or revoked Access Token to make API requests will result in:
App only Access Token (Bearer Token) used on endpoint which doesn’t support application-only auth
Requesting an endpoint which requires a user context (such as statuses/home_timeline
) with a n App only Access Token (Bearer Token) will produce:
Using and generating an app-only Bearer Token
A bearer token allows developers to have a more secure point of entry for using the Twitter APIs, and are one of the core features of OAuth 2.0.
Authentication, which uses a Bearer Token, is also known as application-only authentication. A Bearer Token is a byte array of unspecified format that you generate using a script like a curl command. You can also obtain a Bearer Token from the developer portal inside the keys and tokens section of your App’s settings. More information about this feature can be found on OAuth’s official documentation.
When are they used?
The products that require the use of a Bearer Token are as follows:
- Engagement API
- Premium Search Tweets API
- Account Activity API
- Other APIs that utilize OAuth 2.0 Bearer Token authentication such as v2 and Labs endpoints.
Prerequisites
You will need to sign up for a developer account and to have created a Twitter App. Once you have those, you’ll also need to obtain the API keys found in the developer portal. Follow the steps below:
- Login to your Twitter account on developer.twitter.com.
- Navigate to the Twitter App dashboard and open the Twitter App for which you would like to generate access tokens.
- Navigate to the “keys and tokens” page.
- You’ll find the API keys, user Access Tokens, and Bearer Token on this page.
How to generate a Bearer Token
You can find the Bearer Token for your App with the rest of your “Keys and Tokens”.
Copy the following cURL request into your command line after making changes to the following consumer API keys previously obtained from your Twitter App. Note that the consumer API keys used on this page have been decommissioned and will not work for real requests.
-
API key
<API key>
e.g.xvz1evFS4wEEPTGEFPHBog
-
API secret key
<API secret key>
e.g.L8qq9PZyRg6ieKGEKhZolGC0vJWLw8iEJ88DRdyOg
Here’s an example of how the curl request should look with your API keys entered:
Here is what the response would look like. Note that this is a decommissioned Bearer Token:
{"token_type":"bearer","access_token":"AAAAAAAAAAAAAAAAAAAAAMLheAAAAAAA0%2BuSeid%2BULvsea4JtiGRiSDSJSI%3DEUifiRBkKG5E2XzMDjRfl76ZC9Ub0wnz4XsNiRVBChTYbJcE3F"}
Our Bearer Token used to authenticate to resources with OAuth 2.0 would be:
AAAAAAAAAAAAAAAAAAAAAMLheAAAAAAA0%2BuSeid%2BULvsea4JtiGRiSDSJSI%3DEUifiRBkKG5E2XzMDjRfl76ZC9Ub0wnz4XsNiRVBChTYbJcE3F
OAuth 2.0 Authorization Code Flow with PKCE
Introduction
OAuth 2.0 is an industry-standard authorization protocol that allows for greater control over an application’s scope, and authorization flows across multiple devices. OAuth 2.0 allows you to pick specific fine-grained scopes which give you specific permissions on behalf of a user.
To enable OAuth 2.0 in your App, you must enable it in your’s App’s authentication settings found in the App settings section of the developer portal.
How long will my credentials stay valid?
By default, the access token you create through the Authorization Code Flow with PKCE will only stay valid for two hours unless you’ve used the offline.access
scope.
Refresh tokens
Refresh tokens allow an application to obtain a new access token without prompting the user via the refresh token flow.
If the scope offline.access
is applied an OAuth 2.0 refresh token will be issued. With this refresh token, you obtain an access token. If this scope is not passed, we will not generate a refresh token.
An example of the request you would make to use a refresh token to obtain a new access token is as follows:
App settings
You can select your App’s authentication settings to be OAuth 1.0a or OAuth 2.0. You can also enable an App to access both OAuth 1.0a and OAuth 2.0.
OAuth 2.0 can be used with the Twitter API v2 only. If you have selected OAuth 2.0 you will be able to see a Client ID in your App’s Keys and Tokens section.
Confidential Clients
Confidential clients can hold credentials in a secure way without exposing them to unauthorized parties and securely authenticate with the authorization server they keep your client secret safe. Public clients as they’re usually running in a browser or on a mobile device and are unable to use your client secrets. If you select a type of App that is a confidential client, you will be provided with a client secret.
If you selected a type of client that is a confidential client in the developer portal, you will also be able to see a Client Secret. Your options are Native App, Single page App, Web App, Automated App, or bot. Native App and Single page Apps are public clients and Web App and Automated App or bots are confidential clients.
You don’t need client id for confidential clients with a valid Authorization Header. You still are required to include Client Id in the body for the requests with a public client.
Scopes
Scopes allow you to set granular access for your App so that your App only has the permissions that it needs. To learn more about what scopes map to what endpoints, view our authentication mapping guide.
Scope | Description |
tweet.read | All the Tweets you can view, including Tweets from protected accounts. |
tweet.write | Tweet and Retweet for you. |
tweet.moderate.write | Hide and unhide replies to your Tweets. |
users.read | Any account you can view, including protected accounts. |
follows.read | People who follow you and people who you follow. |
follows.write | Follow and unfollow people for you. |
offline.access | Stay connected to your account until you revoke access. |
space.read | All the Spaces you can view. |
mute.read | Accounts you’ve muted. |
mute.write | Mute and unmute accounts for you. |
like.read | Tweets you’ve liked and likes you can view. |
like.write | Like and un-like Tweets for you. |
list.read | Lists, list members, and list followers of lists you’ve created or are a member of, including private lists. |
list.write | Create and manage Lists for you. |
block.read | Accounts you’ve blocked. |
block.write | Block and unblock accounts for you. |
bookmark.read | Get Bookmarked Tweets from an authenticated user. |
bookmark.write | Bookmark and remove Bookmarks from Tweets |
Rate limits
For the most part, the rate limits are the same as they are authenticating with OAuth 1.0a, with the exception of Tweets lookup and Users lookup. We are increasing the per-App limit from 300 to 900 requests per 15 minutes while using OAuth 2.0 for Tweet lookup and user lookup. To learn more be sure to check out our documentation on rate limits.
Grant types
We only provide authorization code with PKCE and refresh token as the supported grant types for this initial launch. We may provide more grant types in the future.
OAuth 2.0 Flow
OAuth 2.0 uses a similar flow to what we are currently using for OAuth 1.0a. You can check out a diagram and detailed explanation in our documentation on this subject.
Glossary
Term | Description |
Grant types | The OAuth framework specifies several grant types for different use cases and a framework for creating new grant types. Examples include authorization code, client credentials, device code, and refresh token. |
Confidential client | Clients are applications that can securely authenticate with the authorization server, for example, keeping their registered client secret safe. |
Public client | Clients cannot use registered client secrets, such as applications running in a browser or mobile device. |
Authorization code flow | Used by both confidential and public clients to exchange an authorization code for an access token. |
PKCE | An extension to the authorization code flow to prevent several attacks and to be able to perform the OAuth exchange from public clients securely. |
Client ID | Can be found in the keys and tokens section of the developer portal under the header “Client ID.” If you don’t see this, please get in touch with our team directly. The Client ID will be needed to generate the authorize URL. |
Redirect URI | Your callback URL. You will need to have exact match validation. |
Authorization code | This allows an application to hit APIs on behalf of users. Known as the auth_code. The auth_code has a time limit of 30 seconds once the App owner receives an approved auth_code from the user. You will have to exchange it with an access token within 30 seconds, or the auth_code will expire. |
Access token | Access tokens are the token that applications use to make API requests on behalf of a user. |
Refresh token | Allows an application to obtain a new access token without prompting the user via the refresh token flow. |
Client Secret | If you have selected an App type that is a confidential client you will be provided with a “Client Secret” under “Client ID” in your App’s keys and tokens section. |
![](data:image/svg+xml,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 1422 1600%22%3E%3C/svg%3E)
Parameters
To construct an OAuth 2.0 authorize URL, you will need to ensure you have the following parameters in the authorization URL.
Parameter | Description |
response_type | You will need to specify that this is a code with the word “code”. |
client_id | Can be found in the developer portal under the header “Client ID”. |
redirect_uri | Your callback URL. This value must correspond to one of the Callback URLs defined in your App’s settings. For OAuth 2.0, you will need to have exact match validation for your callback URL. |
state | A random string you provide to verify against CSRF attacks. The length of this string can be up to 500 characters. |
code_challenge | A PKCE parameter, a random secret for each request you make. |
code_challenge_method | Specifies the method you are using to make a request (S256 OR plain). |
Authorize URL
With OAuth 2.0, you create an authorize URL, which you can use to allow a user to authenticate via an authentication flow, similar to “Sign In” with Twitter.
An example of the URL you are creating is as follows:
You will need to have the proper encoding for this URL to work, be sure to check out our documentation on the percent encoding.
Additional resources
How to connect to endpoints using OAuth 2.0 Authorization Code Flow with PKCE
How to connect to the endpoints
To authenticate your users, your App will need to implement an authorization flow. This authorization flow lets you direct your users to an authorization dialog on Twitter. From there, the primary Twitter experience will show the authorization dialog and handle the authorization on behalf of your App. Your users will be able to authorize your App or decline permission. After the user makes their choice, Twitter will redirect the user to your App, where you can exchange the authorization code for an access token (if the user authorized your App), or handle a rejection (if the user did not authorize your App).
Working with confidential clients
If you are working with confidential clients, you will need to use a basic authentication scheme for generating an authorization header with base64 encoding while making requests to the token endpoints.
The userid
and password
are separated by a single colon (”:”) character within a base64 encoded string in the credentials.
An example would look like this:
-header 'Authorization: Basic V1ROclFTMTRiVWhwTWw4M2FVNWFkVGQyTldNNk1UcGphUTotUm9LeDN4NThKQThTbTlKSXQyZm1BanEzcTVHWC1icVozdmpKeFNlR3NkbUd0WEViUA=='
If the user agent wishes to send the Client ID “Aladdin” and password “open sesame,” it would use the following header field:
Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
To create the basic authorization header you will need to base64 encoding on your Client ID and Client Secret which can be obtained from your App’s “Keys and Tokens” page inside of the developer portal.
Steps to connect using OAuth 2.0
Step 1: Construct an Authorize URL
Your App will need to build an authorize URL to Twitter, indicating the scopes your App needs to authorize. For example, if your App needs to lookup Tweets, users and to manage follows, it should request the following scopes:
tweet.read%20users.read%20follows.read%20follows.write
The URL will also contain the code_challenge
and state parameters, in addition to the other required parameters. In production you should use a random string for the code_challenge
.
Step 2: GET oauth2/authorize
Have the user authenticate and send the application an authorization code. If you have enabled OAuth 2.0 for your App you can find your Client ID inside your App’s “Keys and Tokens” page.
An example URL to redirect the user to would look like this:
An example URL with offline_access would look like this:
Upon successful authentication, the redirect_uri you would receive a request containing the auth_code parameter. Your application should verify the state parameter.
An example request from client’s redirect would be:
Step 3: POST oauth2/token - Access Token
At this point, you can use the authorization code to create an access token and refresh token (only if offline.access
scope is requested). You can make a POST request to the following endpoint:
https://api.x.com/2/oauth2/token
You will need to pass in the Content-Type
of application/x-www-form-urlencoded
via a header. Additionally, you should have in your request: code
, grant_type
, client_id
and redirect_uri
, and the code_verifier
.
Here is an example token request for a public client:
Here is an example using a confidential client:
Step 4: Connect to the APIs
You are now ready to connect to the endpoints using OAuth 2.0. To do so, you will request the API as you would using [Bearer Token authentication](https://developer.twitter.com(/resources/fundamentals/authentication#app-only-authentication-and-oauth-2-0-bearer-token). Instead of passing your Bearer Token, you’ll want to use the access token you generated in the last step. As a response, you should see the appropriate payload corresponding to the endpoint you are requesting. This request is the same for both public and confidential clients.
An example of the request you would make would look as follows:
Code copied to clipboard
Step 5: POST oauth2/token - refresh token
A refresh token allows an application to obtain a new access token without prompting the user. You can create a refresh token by making a POST request to the following endpoint: https://api.x.com/2/oauth2/token You will need to add in the Content-Type
of application/x-www-form-urlencoded
via a header. In addition, you will also need to pass in your refresh_token, set your grant_type to be a refresh_token
, and define your client_id
.
This request will work for public clients:
Here is an example of one for confidential clients:
Step 6: POST oauth2/revoke - Revoke Token
A revoke token invalidates an access token or refresh token. This is used to enable a “log out” feature in clients, allowing you to clean up any security credentials associated with the authorization flow that may no longer be necessary. The revoke token is for an App to revoke a token and not a user. You can create a revoke token request by making a POST request to the following URL if the App wants to programmatically revoke the access given to it:
https://api.x.com/2/oauth2/revoke
You will need to pass in the Content-Type
of application/x-www-form-urlencoded
via a header, your token, and your client_id.
In some cases, a user may wish to revoke access given to an App, they can revoke access by visiting the connected Apps page.
This request will work for confidential clients:
Additional resources
Basic authentication
Many of Twitter’s enterprise APIs require the use of HTTP Basic Authentication. To make a successful request to an API that requires Basic Authentication, you must pass a valid email address and password combination as an authorization header for each request. The email and password combination are the same ones that you will use to access the enterprise API console, and can be editted from within this console.
When building a request using Basic Authentication, make sure you add the Authentication: Basic HTTP header with encoded credentials over HTTPS.
In the following cURL request example, you would replace <email_address>
and <password>
with your credentiails before sending the request:
APIs that require basic authentication:
- PowerTrack API enterprise
- Decahose stream API enterprise
- 30-Day Search API enterprise
- Full-Archive Search API enterprise
- Historical PowerTrack API enterprise
- Usage API enterprise
OAuth FAQ
General
Technical
OAuth API reference index
OAuth 1.0a
Purpose | Method |
Step 1 of the 3-legged OAuth flow and Sign in with Twitter Allows a Consumer application to obtain an OAuth Request Token to request user authorization. | [POST oauth/request_token]https://developer.x.com/en/docs/basics/authentication/api-reference/request_token) |
Step 2 of the 3-legged OAuth flow and Sign in with Twitter Allows a Consumer application to use an OAuth Request Tokento request user authorization. | GET oauth/authenticate |
Step 2 of the 3-legged OAuth flow and Sign in with Twitter Allows a Consumer application to use an OAuth Request Token to request user authorization. | GET oauth/authorize |
Step 3 of the 3-legged OAuth flow and Sign in with Twitter Allows a Consumer application to exchange the OAuth Request Token for an OAuth Access Token. | POST oauth/access_token |
Allows a registered application to revoke an issued OAuth Access Token. | POST oauth/invalidate_token |
OAuth 2.0 Bearer Token
Purpose | Method |
Allows a registered App to generate an OAuth 2 app-only Bearer Token, which can be used to make API requests on an App’s behalf, without user context. | POST oauth2/token |
Allows a registered App to revoke an issued OAuth 2 app-only Bearer Token. | POST oauth2/invalidate_token |
POST oauth/request_token
Allows a Consumer application to obtain an OAuth Request Token to request user authorization. This method fulfills Section 6.1 of the OAuth 1.0 authentication flow.
We require you use HTTPS for all OAuth authorization steps.
Usage Note: Only ASCII values are accepted for the oauth_nonce
https://api.x.com/oauth/request_token
Response formats | JSON |
Requires authentication? | No |
Rate limited? | Yes |
Name | Required | Description | Example |
---|---|---|---|
oauth_callback | required | For OAuth 1.0a compliance this parameter is required . The value you specify here will be used as the URL a user is redirected to should they approve your application’s access to their account. Set this to oob for out-of-band pin mode. This is also how you specify custom callbacks for use in desktop/mobile applications. Always send an oauth_callback on this step, regardless of a pre-registered callback.We require that any callback URL used with this endpoint will have to be configured within the App’s settings on developer.twitter.com* | http://themattharris.local/auth.php twitterclient://callback |
x_auth_access_type | optional | Overrides the access level an application requests to a users account. Supported values are read or write . This parameter is intended to allow a developer to register a read/write application but also request read only access when appropriate. |
Learn more about how to approve your callback URLs on this page.
Please note - You can view and edit your existing Twitter apps via the Twitter app dashboard if you are logged into your Twitter account on developer.twitter.com.
Request URL: POST https://api.x.com/oauth/request_token
Request POST Body: N/A
Authorization Header: OAuth oauth_nonce="K7ny27JTpKVsTgdyLdDfmQQWVLERj2zAK5BslRsqyw", oauth_callback="http%3A%2F%2Fmyapp.com%3A3005%2Ftwitter%2Fprocess_callback", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1300228849", oauth_consumer_key="OqEqJeafRSF11jBMStrZz", oauth_signature="Pc%2BMLdv028fxCErFyi8KXFM%2BddU%3D", oauth_version="1.0"
Response: oauth_token=Z6eEdO8MOmk394WozF5oKyuAv855l4Mlqo7hhlSLik&oauth_token_secret=Kd75W4OQfb2oJTV0vzGzeXftVAwgMnEK9MumzYcM&oauth_callback_confirmed=true
GET oauth/authorize
Allows a Consumer application to use an OAuth Request Token to request user authorization. This method fulfills Section 6.2 of the OAuth 1.0 authentication flow. Desktop applications must use this method (and cannot use GET oauth / authenticate).
Usage Note: An oauth_callback
is never sent to this method, provide it to [POST oauth / request_token]https://developer.x.com/en/docs/basics/authentication/api-reference/request_token) instead.
https://api.x.com/oauth/authorize
Response formats | JSON |
Requires authentication? | Yes |
Rate limited? | Yes |
Name | Required | Description | Default Value | Example |
force_login | optional | Forces the user to enter their credentials to ensure the correct users account is authorized. | ||
screen_name | optional | Prefills the username input box of the OAuth login screen with the given value. |
Send the user to the oauth/authorize
step in a web browser, including an oauth_token parameter:
https://api.x.com/oauth/authorize?oauth_token=Z6eEdO8MOmk394WozF5oKyuAv855l4Mlqo7hhlSLik
GET oauth/authenticate
Allows a Consumer application to use an OAuth request_token
to request user authorization.
This method is a replacement of Section 6.2 of the OAuth 1.0 authentication flow for applications using the callback authentication flow. The method will use the currently logged in user as the account for access authorization unless the force_login
parameter is set to true
.
This method differs from GET oauth / authorize in that if the user has already granted the application permission, the redirect will occur without the user having to re-approve the application. To realize this behavior, you must enable the Use Sign in with Twitter setting on your application record.
https://api.x.com/oauth/authenticate
Response formats | JSON |
Requires authentication? | Yes |
Rate limited? | Yes |
Name | Required | Description | Default Value | Example |
force_login | optional | Forces the user to enter their credentials to ensure the correct users account is authorized. | true | |
screen_name | optional | Prefills the username input box of the OAuth login screen with the given value. |
Send the user to the oauth/authenticate
step in a web browser, including an oauth_token parameter:
https://api.x.com/oauth/authenticate?oauth_token=Z6eEdO8MOmk394WozF5oKyuAv855l4Mlqo7hhlSLik
POST oauth/access_token
Allows a Consumer application to exchange the OAuth Request Token for an OAuth Access Token. This method fulfills Section 6.3 of the OAuth 1.0 authentication flow.
https://api.x.com/oauth/access_token
Response formats | JSON |
Requires authentication? | Yes |
Rate limited? | Yes |
Name | Required | Description | Default Value | Example |
oauth_token | required | The oauth_token here must be the same as the oauth_token returned in the request_token step. | ||
oauth_verifier | required | If using the OAuth web-flow, set this parameter to the value of the oauth_verifier returned in the callback URL. If you are using out-of-band OAuth, set this value to the pin-code. For OAuth 1.0a compliance this parameter is required. OAuth 1.0a is strictly enforced and applications not using the oauth_verifier will fail to complete the OAuth flow. |
POST https://api.x.com/oauth/access_token?oauth_token=qLBVyoAAAAAAx72QAAATZxQWU6P&oauth_verifier=ghLM8lYmAxDbaqL912RZSRjCCEXKDIzx
From PIN-based POST https://api.x.com/oauth/access_token?oauth_token=9Npq8AAAAAAAx72QBRABZ4DAfY9&oauth_verifier=4868795
oauth_token=6253282-eWudHldSbIaelX7swmsiHImEL4KinwaGloHANdrY&oauth_token_secret=2EEfA6BG5ly3sR3XjE0IBSnlQu4ZrUzPiYTmrkVU&user_id=6253282&screen_name=twitterapi
POST oauth/invalidate_token
Allows a registered application to revoke an issued OAuth access_token by presenting its client credentials. Once an access_token has been invalidated, new creation attempts will yield a different Access Token and usage of the invalidated token will no longer be allowed.
https://api.x.com/1.1/oauth/invalidate_token
Response formats | JSON |
Requires authentication? | Yes - User context with the access tokens that you would like to invalidate |
Rate limited? | Yes |
Example error response after token has been invalidated
POST oauth2/token
Allows a registered application to obtain an OAuth 2 Bearer Token, which can be used to make API requests on an application’s own behalf, without a user context. This is called Application-only authentication.
A Bearer Token may be invalidated using oauth2/invalidate_token. Once a Bearer Token has been invalidated, new creation attempts will yield a different Bearer Token and usage of the previous token will no longer be allowed.
Only one bearer token may exist outstanding for an application, and repeated requests to this method will yield the same already-existent token until it has been invalidated.
Successful responses include a JSON-structure describing the awarded Bearer Token.
Tokens received by this method should be cached. If attempted too frequently, requests will be rejected with a HTTP 403 with code 99.
https://api.x.com/oauth2/token
Response formats | JSON |
Requires authentication? | Yes - Basic auth with your API key as your username and API key secret as your password |
Rate limited? | Yes |
Name | Required | Description | Default Value | Example |
grant_type | required | Specifies the type of grant being requested by the application. At this time, only client_credentials is allowed. See Application-Only Authentication for more information. | client_credentials |
Example response:
POST oauth2/invalidate_token
Allows a registered application to revoke an issued oAuth 2.0 Bearer Token by presenting its client credentials. Once a Bearer Token has been invalidated, new creation attempts will yield a different Bearer Token and usage of the invalidated token will no longer be allowed.
Successful responses include a JSON-structure describing the revoked Bearer Token.
https://api.x.com/oauth2/invalidate_token
Response formats | JSON |
Requires authentication? | Yes - oAuth 1.0a with the application’s consumer API keys and the application owner’s access token & access token secret |
Rate limited? | Yes |
Name | Required | Description |
---|---|---|
access_token | required | The value of the bearer token that you would like to invalidate |