In this tutorial we’ll go through an example of how to implement JWT (JSON Web Token) authentication with refresh tokens in a Node.js + MongoDB API.

For an extended example that includes email sign up, verification, forgot password and user management (CRUD)

The example API has the following endpoints/routes to demonstrate authenticating with JWT, refreshing and revoking tokens, and accessing secure routes:

  • /users/authenticate - public route that accepts HTTP POST requests containing a username and password in the body. If the username and password are correct then a JWT authentication token and the user details are returned in the response body, and a refresh token cookie (HTTP Only) is returned in the response headers.

  • /users/refresh-token - public route that accepts HTTP POST requests with a refresh token cookie. If the cookie exists and the refresh token is valid then a new JWT authentication token and the user details are returned in the response body, a new refresh token cookie (HTTP Only) is returned in the response headers and the old refresh token is revoked.

  • /users/revoke-token - secure route that accepts HTTP POST requests containing a refresh token either in the body or in a cookie, if both are present the token in the body is used. If the refresh token is valid and active then it is revoked and can no longer be used to refresh JWT tokens.

  • /users - secure route that accepts HTTP GET requests and returns a list of all the users in the application if the HTTP Authorization header contains a valid JWT token. If there is no auth token or the token is invalid then a 401 Unauthorized response is returned.

  • /users/{id} - secure route that accepts HTTP GET requests and returns the details of the user with the specified id.

  • /users/{id}/refresh-tokens - secure route that accepts HTTP GET requests and returns a list of all refresh tokens (active and revoked) of the user with the specified id.

  • /api-docs - swagger documentation for the api

#node #nodjs #mongodb

Node.js + MongoDB API - JWT Authentication with Refresh Tokens
31.30 GEEK