Step-by-Step Guide to Implementing OAuth2 in a Node.js Application

Step-by-Step Guide to Implementing OAuth2 in a Node.js Application


OAuth2 is an authorization framework that allows applications to access a user’s resources stored in another application without the need to share the user’s credentials. In this blog post, we will go through the process of implementing OAuth2 in a Node.js application.

Step 1: Create a new Node.js project

Create a new Node.js project using the following command in your terminal:

mkdir oauth2-example
cd oauth2-example
npm init -y

Step 2: Install Dependencies

Next, install the necessary dependencies for our project:

npm install express express-session request request-promise dotenv

Here, we are installing the express, express-session, request, request-promise and dotenv packages. express and express-session are used to set up a server to receive and respond to HTTP requests. request and request-promise are used to make HTTP requests to the OAuth2 provider. dotenv is used to manage environment variables.

Step 3: Configure Environment Variables

Create a .env file in the root directory of your project and add the following variables:

CLIENT_ID=<your_client_id_here>
CLIENT_SECRET=<your_client_secret_here>
REDIRECT_URI=http://localhost:3000/callback

Replace <your_client_id_here> and <your_client_secret_here> with the client ID and client secret provided by the OAuth2 provider. REDIRECT_URI is the URL where the user will be redirected after the authorization process.

Step 4: Set Up Express Server

Create a new file called app.js and add the following code:

require('dotenv').config()

const express = require('express')
const session = require('express-session')
const request = require('request-promise')

const app = express()

app.use(session({
  secret: 'your_secret_here',
  resave: false,
  saveUninitialized: true
}))

app.get('/', (req, res) => {
  res.send('Hello World!')
})

app.listen(3000, () => {
  console.log('Server listening on http://localhost:3000')
})

Here, we are configuring the express server to use the express-session middleware, which is required to manage user sessions. We also define a route for the home page and start the server listening on port 3000.

Step 5: Implement Authorization Flow

Add the following code to the app.js file to implement the authorization flow:

app.get('/login', (req, res) => {
  const authEndpoint = 'https://oauth2-provider.com/authorize'

  const queryParams = new URLSearchParams({
    response_type: 'code',
    client_id: process.env.CLIENT_ID,
    redirect_uri: process.env.REDIRECT_URI
  })

  const authUrl = `${authEndpoint}?${queryParams}`

  res.redirect(authUrl)
})

app.get('/callback', async (req, res) => {
  const tokenEndpoint = 'https://oauth2-provider.com/token'

  const { code } = req.query

  const requestBody = {
    grant_type: 'authorization_code',
    code,
    client_id: process.env.CLIENT_ID,
    client_secret: process.env.CLIENT_SECRET,
    redirect_uri: process.env.REDIRECT_URI
  }

  const options = {
    method: 'POST',
    uri: tokenEndpoint,
    form: requestBody,
    json: true
  }

  try {
    const response = await request(options)

    req.session.accessToken = response.access_token
    req.session.refreshToken = response.refresh_token

    res.redirect('/user')

} catch (err) {
res.send('Error retrieving access token')
}
})

app.get('/user', async (req, res) => {
const userEndpoint = 'https://oauth2-provider.com/userinfo'

const options = {
headers: {
Authorization: Bearer ${req.session.accessToken}
},
json: true
}

try {
const response = await request.get(userEndpoint, options)
res.send(response)
} catch (err) {
res.send('Error retrieving user info')
}
})

Here, we define two routes: /login and /callback. /login redirects the user to the authorization endpoint of the OAuth2 provider with the necessary query parameters, including the response_type, client_id, and redirect_uri.

After the user grants access, the OAuth2 provider will redirect the user back to the specified redirect_uri.

/callback is the endpoint where the OAuth2 provider will redirect the user after the authorization process is complete.

We extract the authorization code from the query parameters and exchange it for an access token and refresh token from the token endpoint of the OAuth2 provider.

We then store the access token and refresh token in the user’s session and redirect the user to the /user endpoint.

Step 6: Test the Application

Start the server using the following command:

node app.js

Open your web browser and go to http://localhost:3000/login. You should be redirected to the OAuth2 provider’s authorization page. After granting access, you should be redirected back to the application and see the user’s information displayed on the page.


Conclusion

In this blog post, we have learned how to implement OAuth2 in a Node.js application. We covered the necessary steps to configure the application, set up the express server, and implement the authorization flow using the express-session and request-promise packages. By following these steps, you can easily integrate OAuth2 into your Node.js application.

Did you find this article valuable?

Support The Code Crafters by becoming a sponsor. Any amount is appreciated!