Hướng dẫn thử thách
1 / 1
Authentication and Authorization Review
## Authentication vs Authorization
**Authentication** is the process of verifying a user's identity. It answers *"Is this person who they claim to be?"* When a user logs in, the backend server compares their credentials against the records stored during registration.
Backend developers use three main categories of authentication factors:
- **Something you know:** A password, PIN, or security question answer.
- **Something you have:** An SMS code on a smartphone, or a temporary token from an authenticator app.
- **Something you are:** Biometric data like a fingerprint or facial recognition scan.
**Authorization** takes over after authentication and decides what the authenticated user is allowed to do. It answers *"What permissions does this identity have?"* Common roles include:
- **Standard User:** Can edit their own profile, but cannot view other users' private data.
- **Editor:** Can write and publish content, but cannot delete the codebase.
- **Admin:** Has full clearance to modify databases, delete users, and change system-wide settings.
**Authentication must always happen first, then authorization.** You cannot decide what permissions to grant until you know who the user is.
## JSON Web Tokens (JWTs)
A JWT is a digital keycard the server issues to a user after a successful login. The user presents it on every subsequent request to prove their identity without re-entering their password.
The four-step JWT flow:
1. **Login:** The user sends credentials to the server.
2. **Issue:** The server verifies the credentials and generates a JWT, then sends it back.
3. **Storage:** The client stores the JWT, typically in a browser cookie or local storage.
4. **Request:** For every future request to a protected route, the client sends the JWT along and the server verifies it.
A JWT consists of three parts separated by two dots:
- **Header:** Encoded JSON declaring the token type (JWT) and the hashing algorithm used, such as HMAC SHA256.
- **Payload:** Encoded JSON containing claims about the user, like the user ID, username, or role. The header and payload are Base64 encoded, not encrypted, so never store sensitive data like passwords here.
- **Signature:** Created by hashing the encoded header and payload together with a secret key known only to the server. If the payload is tampered with, the signature won't match and the server rejects the request with a `401 Unauthorized` response.
JWTs enable **stateless authentication**. The server does not need to store session data in a database because the signature proves it created the token.
## Cross-Site Request Forgery (CSRF)
CSRF is an attack that forces an authenticated user to unknowingly execute unwanted actions on a web application. A malicious website tricks the victim browser into sending a fraudulent request to a backend server, exploiting the fact that browsers automatically attach cookies to any request going to the target server.
**Example attack flow:**
1. You log into, say, `trusted-bank.com`. The bank stores a session token in your browser cookie.
2. Without logging out, you visit `evil-hacker-site.com`.
3. The malicious site silently submits a request to `trusted-bank.com/transfer?amount=1000&to=hacker`.
4. Your browser automatically appends your bank session cookie, so the server processes the request.
The malicious site cannot read your cookie. It simply piggybacks on the fact that your browser automatically attaches cookies to any request going to the target server.
**Defenses against CSRF:**
- **`SameSite=Strict`:** The browser never sends the cookie if the request originates from a third-party website.
- **`SameSite=Lax`:** Allows cookies on safe navigation (clicking a link), but blocks them on cross-site form submissions and API requests.
- **CSRF Tokens:** When a user loads a page, the server generates a random, unique, and unpredictable token and attaches it to the frontend form or session. The client must include it in the request headers or form data. Because a malicious site cannot access the frontend to copy the token, forged requests fail validation.
## Passport.js
Passport.js is an authentication middleware for Node.js that standardizes how you authenticate requests using modular plugins called **Strategies**. With over 500 strategies available, you can add any authentication method by installing the relevant package:
- `passport-local`: username and password against your own database.
- `passport-jwt`: validates JSON Web Tokens on protected API routes.
- `passport-google-oauth20`: log in with Google accounts.
- `passport-github2`: log in with GitHub accounts.
Install the core package and a strategy:
```bash
npm install passport passport-local
```
Wire Passport into your Express app before defining routes:
```js
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
app.use(passport.initialize());
passport.use(new LocalStrategy((username, password, done) => {
// database look-up and password verification logic
}));
```
Protect a login route with Passport as middleware:
```js
app.post('/login', passport.authenticate('local'), (req, res) => {
res.send(`Welcome back, ${req.user.username}!`);
});
```
After successful authentication, Passport automatically handles **session management** (stores user data in the session cookie) and **request decoration** (attaches the user object to `req.user` for use in subsequent route handlers).
## Helmet.js
Helmet.js is a security middleware collection for Node.js that protects your application by automatically setting, modifying, or removing HTTP response headers that Express exposes by default.
Install and apply it in one step:
```bash
npm install helmet
```
```js
const helmet = require('helmet');
app.use(helmet());
```
Placing `app.use(helmet())` at the top of your middleware stack applies these protections to every response:
- **X-Powered-By removed:** Express advertises its presence by default with `X-Powered-By: Express`. Helmet removes this header, preventing attackers from targeting version-specific vulnerabilities.
- **Content-Security-Policy set:** Restricts where the browser can load scripts, images, and styles from, defending against Cross-Site Scripting (XSS) attacks.
- **X-Frame-Options set to SAMEORIGIN:** Prevents your site from being embedded in an external iframe, blocking clickjacking attacks.
- **Strict-Transport-Security set:** Forces browsers to communicate with your server over HTTPS only, protecting data from interception on untrusted networks.
Nhiệm vụ của bạn
Review the authentication and authorization concepts covered in the lectures before taking the quiz.
Vượt qua bài kiểm tra hiện tại để mở khóa bài tiếp theo.
main.sql
UTF-8 • Tab Size: 2Kiểm tra bài:⌘↵