Express middleware implementation for Twitter OAuth2.0 Client

56
3 min readJan 15, 2022

--

It has been announced that Twitter OAuth 2.0 will be officially launched on December 15, 2021.

So I published a Node.js middleware implementation that makes it easier to use Twitter OAuth 2.0.

This module supports the following grant type available on twitter:

(The only new addition is the Authorization Code Grant with PKCE, but Twitter has also had a Client Credentials Grant available for some time.)

In this article, I will explain how to use this module.

Authorization Code Grant with PKCE

First, check the Developer Portal for some necessary parameters (client_id, client_secret and redirect_uri).

Developer Portal

client_id and client_secret

The client_id and client_secret can be checked in the order [Key and tokens] > [OAuth 2.0 Client ID and Client Secret].

redirect_uri

The redirect_uri can be registered and confirmed in the order [Settings] > [User authentication settings] > [general authentication settings].
You can also check the [Type of App] here. If you have selected Public Client, the authentication by client_secret will be omitted.

You are now ready to get Client running!
Now let’s run the following command to see how it works.

$ git clone https://github.com/kg0r0/twitter-oauth2.git
$ cd twitter-oauth2/example/
$ npm install
$ export CLIENT_ID=<YOUR_CLIENT_ID>
$ export CLIENT_SECRET=<YOUR_CLIENT_SECRET>
$ export REDIRECT_URI=http://localhost:3000
$ npm run start
> example@0.1.4 start:authz
> ts-node src/authz.ts
listen port: 3000
received tokens {"token_type":"bearer","expires_at":1642252026,"access_token":"<YOUR-ACCESS-TOKEN>","scope":"users.read tweet.read offline.access","refresh_token":"YOUR-REFRESH-TOKEN"}

The various tokens have been retrieved and output to the console log. You can now access the Twitter API based on the scope!

Client Credentials Grant

The Client Credentials Grant uses a different set of credentials than in the previous section.

It can be checked in the order [Consumer Keys]>[API Key and Secret].

You are now ready to get Client running!
Now let’s run the following command to see how it works.

$ git clone https://github.com/kg0r0/twitter-oauth2.git
$ cd twitter-oauth2/example/
$ npm install
$ export CONSUMER_KEY=<YOUR_CONSUMER_KEY>
$ export CONSUMER_SECRET=<YOUR_CONSUMER_SECRET>
$ npm run start:cc
> example@0.1.4 start:authz
> ts-node src/authz.ts
listen port: 3000
received tokens {"token_type":"bearer","access_token":"<YOUR-ACCESS-TOKEN>"}

You can now access the Twitter API!

Thanks for your feedback and contribution to this module! Please feel free to open issues and send pull-requests.

References

--

--

56
56

No responses yet