DEV Community

Sumit Chahar
Sumit Chahar

Posted on

Creating module for our Github OAuth strategy

In the previous article we set up our routes in the index router file. Now we need to create the strategy to use for our Github OAuth application from passport.js.

What is a auth Strategy ?

Strategies are a defined authentication mechanism which is responsible for handling auth requests. A strategy provides information on what basis of data we provide like client_id, client_secret to verify the application with these credentials.

In our Github strategy we need to pass our client_id, client_secret which are required to verify the application and if the application is registered with Github OAuth or not and only then the OAuth flow proceeds. We also pass a third param i.e., callback_url to which we are redirected after the auth process has ended.

The Github strategy will also return us a callback function with accessToken, refreshToken, profile and data. We can perform any operation we want with the data we get from this callback.

We can use the accessToken and refreshToken to authenticate the user once we have them stored in our local database in case we don't want our user to login by going to the Github consent screen every time they want to login.

We will create a modules folder in our project folder and create a file name for example passport.js in the folder. The file will have the following structure.

before we start writing our module file we will need to add it to app.js and preferably before we are initialising our application. As we want to make sure that the first time when our application is initialised our strategy in the module is already stored in the memory.

Image description

After importing it in app.js we can proceed further.

Image description

In the above file,

  • We are redirected to the callback url after the auth process is complete the /auth/github/callback is already present in our index.js file.

  • Next, we need to use the callback function that contains the user data and tokens in the Github strategy and create a user and store it in our local database.

Go to next article 👉

Top comments (0)