Securing API endpoints in Node.js with OAuth 2.0

In this blog post I explain how to secure an API with OAuth 2.0 authorization framework as well as implementing changes in a Web app/page to allow users access to that API. This implementation uses JavaScript in frontend and backend (Node.js). The demo runs on a serverless platform (Vercel), but you can run the same code with minor changes on express.js or other Node.js servers.

Workflow

  • User authenticates himself via a login form.
  • Server verifies user's credentials and if they are valid it generates access and refresh tokens. Access token which has a short lifetime is sent to browser in response body while refresh token is set in a httpOnly cookie in response header.
  • Our app fetches access token and sets it in authorization header of all requests to the api.
  • When a request reaches API server it validates access token in a middleware and if it's valid let request continue to the api endpoint. If access token has expired or is missing, it returns an error.
  • If request to API returns error, our app sends a "GET" request to server to fetch new tokens. Since browser hast refresh token in a cookie, the cookie is submitted with this request automatically.
  • Server fetches refresh token from cookie and if it's valid it generates access and refresh tokens like before.

Implementation of OAuth in a serverless Node.js app:

Implementation of OAuth in a serverless API: