Urgent.News

What's breaking now, across thousands of outlets.

Tech

Implementing Authentication in Node.js Apps (JWT, OAuth 2.0, bcrypt)

The complete flow: password hashing, JWTs, refresh tokens, OAuth 2.0, and the hardening details most tutorials skip. Every Node.js authentication tutorial covers the happy path: hash the password with bcrypt, sign a JWT, verify it in middleware, done. Then you ship it, and within a month something hurts. A token in localStorage gets stolen by an XSS payload. A refresh token that never expires…

Authentication in Node.js applications involves several security measures to protect user data and maintain a robust system. The complete implementation covers password hashing, JWTs, refresh tokens, OAuth 2.0, and various hardening details that are often overlooked in tutorials.

The process begins with setting up the project and dependencies, including express for the web framework, jsonwebtoken for signing and verifying JWTs, bcrypt for password hashing, cookie-parser for reading cookies, passport for OAuth 2.0 integration with Google, and dotenv for loading secrets from a .env file.

When handling passwords, it is crucial to never store plaintext passwords or invented hash values. Instead, use bcrypt, which is intentionally slow for added security. The cost factor is set to 12, resulting in a hashing time of around 300 milliseconds. This slower process makes it significantly more difficult for attackers attempting dictionary attacks, as each guess takes more time.

Upon successful login, two tokens are issued: an access token with a 15-minute lifespan and a refresh token with a 7-day lifespan. The access token is signed using JWT and stored in HTTPOnly cookies for added security. The refresh token is generated using crypto.randomUUID() and hashed using bcrypt before storing it in the database. This token is used for subsequent access when a new access token is required.

OAuth 2.0 is implemented using passport and passport-google-oauth20, allowing users to authenticate with Google. The refresh token is stored in the database, hashed, and associated with the user's ID and an expiration timestamp. The Authorization header is used for every API route, requiring the authenticate middleware to verify the tokens and protect the application.

By following this comprehensive approach to authentication, developers can ensure their Node.js applications remain secure and resilient against various threats.

Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.

Read the original at dev.to →

More in Tech

More from Friday 4 September →