How to do Authorization in MERN Stack?

Nadim Chowdhury - Nov 5 '23 - - Dev Community

Authentication in a MERN (MongoDB, Express.js, React, Node.js) stack application usually follows this pattern:

  1. User Registration and Login:
  2. The user provides their email/username and password.
  3. Passwords are hashed using a library like bcrypt before they're stored in MongoDB.
  4. The backend verifies the hashed password during login.

  5. Token Generation:

  6. Once verified, the server generates a JSON Web Token (JWT) and sends it back to the client.

  7. Libraries like jsonwebtoken are popular for handling JWTs in Node.js.

  8. Token Storage:

  9. On the client side (React), the JWT is typically stored in local storage or cookies.

  10. For added security against cross-site scripting (XSS), HTTP-only cookies can be used. This way, the token isn't accessible via JavaScript on the client side.

  11. Authenticated Requests:

  12. For subsequent requests that require authentication, the client attaches the JWT as a header (usually an Authorization header).

  13. The server verifies the JWT on every request to ensure it's valid and belongs to the right user.

  14. Protected Routes:

  15. On the server side (Express.js), middleware functions can be used to protect routes. If a request doesn't have a valid token, the server will return a 401 Unauthorized error.

  16. On the client side (React), you can create protected routes using React Router by checking if the user is authenticated before rendering a component.

  17. Logging Out:

  18. On the client side, logging out might simply involve removing the JWT from local storage or cookies.

  19. If you're using token blacklisting (where invalidated tokens are stored in a list/database to prevent their use), you'd also add the token to the blacklist at this stage.

  20. Token Expiration:

  21. JWTs typically have an expiration time. When they expire, the user needs to log in again or refresh the token.

  22. Refresh tokens can be used to get a new access token without having the user log in again.

Remember, while JWTs provide a way to authenticate requests, they shouldn't be used to store sensitive or confidential information since they can be decoded easily.

Finally, always ensure that connections are secured using HTTPS to prevent man-in-the-middle attacks. This is especially crucial during the login phase where passwords might be sent from the client to the server.

This is a basic overview, and depending on the specifics of your application, additional security measures and considerations might be necessary.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .