DevAcademy
LearnNode.jsAuthentication Basics
AdvancedNode.js

Authentication Basics

Understand the difference between authentication and authorization, and common ways to implement login.

Reading Time

12 min

Lesson

Lesson 29 of 34

Authentication vs Authorization

Authentication answers "who are you?" — verifying identity, typically via a password or a third-party login. Authorization answers "what are you allowed to do?" — checking permissions after identity is already known. They are related but distinct concerns.

Common Authentication Approaches

ApproachHow It Works
Session-basedServer stores session state, client holds a session ID cookie
Token-based (JWT)Server issues a signed token the client sends with every request
OAuth / Social loginDelegating identity verification to Google, GitHub, etc.

A Typical Login Flow

A user submits credentials, the server verifies them against the database (comparing a hashed password, covered next), and on success issues something the client can use to prove its identity on future requests — a session cookie or a token.

A Basic Login Route

Try it yourself — edit and run

Console Output

Click “Run” to see the console output here.

Never Reveal Which Part of the Login Failed

Return the same generic error ("Invalid credentials") whether the email doesn't exist or the password is wrong — telling an attacker "no such user" vs "wrong password" separately makes it trivial to enumerate valid accounts.

Best Practice

Rarely build authentication entirely from scratch for a real production app — established libraries (Passport.js) or hosted services (Auth0, Clerk) handle a huge amount of nuanced security detail that's easy to get subtly wrong on your own.

Interview Questions

Quick Quiz

1. What is the difference between authentication and authorization?

2. Why return the same generic error for "user not found" and "wrong password"?

3. Why is it often recommended to use an established library or service for authentication instead of building it entirely from scratch?