(Part 3) Getting Twitter Access Token
Part 3 of the Twitter OAuth 2.0 series. We will learn how to get the Twitter Access Token so we can make requests to the Twitter API.
Tags
TLDR 🥱!!!
All you need to do is send a POST request to Twitter’s oauth2/token endpoint :-
https://api.twitter.com/2/oauth2/token
.
The Authorization header should include the client_id
and client_secret
as a base64 encoded string :-
“Basic” + base_64_encoded_string(client_id:client_secret)
The request body should include the code
, client_id
, redirect_uri
, grant_type
, and code_verifier
.
If everything goes right 🎉, you’ll get yo hands on that Access Token and you’re ready for last Part-4 of this series.
And if something went wrong 😓, then keep reading 👇🏻.
Prerequisites 📝
You’ve got the code
after successfully login in with Twitter.
It’s time to get the Access Token or Bearer Token (same sh*t in this case 😒).
Using the Twitter Code 🚀
Straight up, the strategy is to send the code
& the code_challenge
to a server endpoint,
and then the server will use the Client Secret to get the Access Token from Twitter.
Btw, if you’re like, “What the fu#c is going on? 🤔”, then just go back to the last Part-2.
-
Client Secret is a secret key that only the server should know. That’s why I didn’t directly use it in the frontend (although you sure can, but just for a demo or something 🤷🏻♂️).
That’s also the reason why I’m using Svelte here, because I can simply write API endpoints in the same codebase. -
I also said “it’s better to generate
code_challenge
server side and send it to the frontend when required.”
I guess you can already see why. It’s much better for security reasons 💪🏻, you can generate a new challenge for each login (for every user), and also we will not have to send it to the server again.
Note :- At any point, if you wanna just look at the code, jump right to the end of this post
So I’ve made a little button again 🪙 Get Access Token
.
All it does is sends a fetch
request to the backend server endpoint and waits for the response.
The server is where all the magic happens. Let’s break 🔨 it down a bit more.
Here’s the server code from my Svelte project :-
DO NOT COPY DIS CODE 🙅🏻♂️, It’s just for reference, like psuedo code. Full working code at the end of post
clientId = "Ty1yWm02dFA1NDlGb29XZkRIYS06MTpjaQ"; clientSecret = "Sfnbb5PCEVjb8FnDNuLphkrqu4HraQ2TSe_qFf8F5XV4GyqAL5"; { code, codeChallenge } = fromFrontend; // we'll send this 👇🏻 data to Twitter's oauth2/token endpoint requestData = { code: code, client_id: clientId, code_verifier: codeChallenge, grant_type: "authorization_code", redirect_uri: "http://localhost:5173" }; authorization = `Basic` + `${base64EncodedString(`{clientId}:{clientSecret}`)}`; const response = serverPostRequest( url: "https://api.twitter.com/2/oauth2/token", headers: { Content-Type: "application/x-www-form-urlencoded", Authorization: authorization, }, body: requestData, ); responseData = response.json();
- The server receives the
code
andcodeChallenge
from the frontend. - It then sends a POST request to Twitter’s
oauth2/token
endpoint with all the necessary data.
Note: The twitter’s oauth url might change in future, so always check the official documentation for the latest url. - Also Note We’ve encoded the
client_id
andclient_secret
in the Authorization header as base64 string, because that’s what Twitter’s API requires.
And that’s it, fire the fu#king thing and you’ll get the Access Token 🪙.
Twitter Access Token 🪙
The X-Force will send you this JSON response 👇🏻
{ token_type: "bearer", expires_in: 7200, access_token: "bXBUVUNFRWRvS2haX2NaLW95ZXhxaWg2bl9RYXZIb1FIckxYTmtwTU81UENKOjE3MTAwNzU1MjA0NDY6MToxOmF0OjE", scope: "follows.read tweet.write users.read tweet.read follows.write", };
,that is if everything went right 🤞🏻.
Only The Code 😒
Code for the 🪙 Get Access Token
button 👇🏻
async function fetchToken() { const data = await fetch("/twitter-access-token", { method: "POST", body: JSON.stringify({ code, codeChallenge, }), }); const json = await data.json(); accessToken = json.access_token; }
And the server code 👇🏻
// src/routes/twitter-access-token/+server.ts import type { RequestEvent, RequestHandler } from "@sveltejs/kit"; const clientId = "Ty1yWm02dFA1NDlGb29XZkRIYS06MTpjaQ"; const clientSecret = "Sfnbb5PCEVjb8FnDNuLphkrqu4HraQ2TSe_qFf8F5XV4GyqAL5"; export const POST: RequestHandler = async ({ request }: RequestEvent) => { const { code, codeChallenge } = await request.json(); const requestData = new URLSearchParams({ code, // short hand syntax for code: code client_id: clientId, redirect_uri: "http://localhost:5173", grant_type: "authorization_code", code_verifier: codeChallenge, }); const authorization = `Basic ${btoa(`${clientId}:${clientSecret}`)}`; const response = await fetch("https://api.twitter.com/2/oauth2/token", { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded", Authorization: authorization, }, body: requestData, }); const responseData = await response.json(); return new Response(JSON.stringify(responseData), { status: 200 }); };
- If the Code to you looks “ugly” here, then copy the fu*kng thing in your own editor for proper formatting, I’m working with limited space 😒.
That’s it!, thanks 🤗 for reading all the way till down here. Now quickly jump to the next part.