Authentication
- Authentication
- Node.js
The process of verifying that a request comes from the identity it claims, and how a stateless server keeps a user signed in after the first check.
What you'll understand
- What authentication actually proves
- The difference between authentication and authorization
- How a server keeps you signed in without re-checking your password each time
Explanation
Authentication answers one question: who are you? It is the process of verifying that a request comes from the identity it claims. It is distinct from authorization, which decides what that identity is allowed to do. You authenticate first (prove identity), then authorize (check permission).
A typical flow: a user proves their identity once by presenting credentials, usually an email and password, and the server checks them. Because HTTP is stateless, the server cannot remember that check on the next request. So it issues the client a credential to present on future requests: a session identifier stored in a cookie, or a token such as a JWT. Each later request carries that credential, and the server verifies it instead of re-checking the password every time.
The security of authentication rests on two things: verifying the initial credentials safely, which means never storing passwords in plain text (see Related Topics), and protecting the issued credential in transit and at rest. If either leaks, an attacker can impersonate the user.
Examples
This TypeScript example verifies a login by comparing a submitted password against a stored hash, then issues a session credential:
async function login(email: string, password: string) {
const user = await users.findByEmail(email);
if (!user) throw new Error('Invalid credentials');
const valid = await verifyPassword(password, user.passwordHash);
if (!valid) throw new Error('Invalid credentials');
return issueSession(user.id); // e.g. a signed token or a session id
}Notice the identical error for a missing user and a wrong password. This avoids revealing which emails are registered.
Common mistakes
- Confusing authentication with authorization. Proving who you are is not the same as being allowed to act.
- Telling the client whether the email or the password was wrong, which helps attackers find valid accounts.
- Re-sending the password on every request instead of issuing a credential once and verifying it thereafter.
- Storing or logging raw passwords or tokens.
Best practices
- Return a single generic message for any failed login.
- Verify credentials over an encrypted connection only.
- Issue a short-lived credential after login and verify it on each request.
- Never store passwords in plain text; store slow salted hashes (see Related Topics).
Further reading
- OWASP, Authentication Cheat Sheet — https://cheatsheetseries.owasp.org/cheatsheets/Authentication_Cheat_Sheet.html