Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"label": "Authentication",
"position": 10,
"link": {
"type": "generated-index",
"title": "Authentication: Securing Your Application",
"description": "Learn how to implement secure authentication mechanisms in your applications. This track covers everything from basic login systems to advanced topics like OAuth, JWT, and multi-factor authentication."
}
}
Original file line number Diff line number Diff line change
@@ -1 +1,98 @@
<ComingSoon />
---
title: "Authentication Best Practices"
sidebar_label: "7. Best Practices"
sidebar_position: 7
description: "Essential security checklist for building professional and secure authentication systems."
tags: ["authentication", "security", "best practices", "full-stack development"]
keywords: ["authentication best practices", "password security", "HTTPS", "JWT security", "rate limiting", "multi-factor authentication", "RBAC", "security checklist"]
---

In the world of security, we assume that attackers are smart and persistent. Following these rules will protect your application from 99% of common attacks.

## 1. Password Security

### Use Salted Hashing

As we learned, never store passwords as plain text. Use **Bcrypt** with at least **10-12 salt rounds**.

### Enforce Strong Password Policies

Don't let users use `password123`. Require a mix of:
* Minimum 8-12 characters.
* At least one uppercase letter.
* At least one number and one special character.

## 2. Transport & Storage

### HTTPS is Non-Negotiable
Without SSL/TLS (HTTPS), passwords and JWTs are sent across the internet in plain text. Any "man-in-the-middle" can steal them. **Always use HTTPS in production.**

### Use HttpOnly and Secure Cookies
If you store tokens in cookies, set these flags:
* `HttpOnly`: Prevents JavaScript from reading the cookie (stops XSS attacks).
* `Secure`: Ensures the cookie is only sent over HTTPS.
* `SameSite=Strict`: Prevents CSRF (Cross-Site Request Forgery) attacks.

## 3. Handling JWTs (Tokens)

### Keep Secrets Secret
Never hardcode your `JWT_SECRET`. Use environment variables (`.env`) and make sure `.env` is in your `.gitignore`.

### Use Short Expiration Times
Tokens should not last forever. A good standard is **15 minutes to 1 hour** for access tokens.

## 4. Protection Against Attacks

### Rate Limiting
Prevent "Brute Force" attacks (where a bot tries thousands of passwords) by limiting how many requests an IP can make to your `/login` route.

```javascript title="rateLimiter.js"
const rateLimit = require('express-rate-limit');

const loginLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 5, // Limit each IP to 5 login requests per window
message: "Too many login attempts, please try again after 15 minutes"
});

app.use('/api/auth/login', loginLimiter);

```

### Generic Error Messages

Never tell a hacker *which* part of the login was wrong.

* **Bad:** "User not found" or "Incorrect password."
* **Good:** "Invalid email or password."

## 5. Multi-Factor Authentication (MFA)

For high-security apps, a password isn't enough. Implement MFA using:

* **TOTP:** Apps like Google Authenticator.
* **Email/SMS:** Sending a one-time code (OTP).

## 6. The "Master" Checklist

| Category | Requirement | Check |
| --- | --- | --- |
| **Passwords** | Hashed with Bcrypt + Salt | ☐ |
| **Transport** | All traffic over HTTPS | ☐ |
| **Tokens** | Short-lived + Securely stored | ☐ |
| **Database** | Roles (RBAC) implemented | ☐ |
| **Monitoring** | Logs for failed login attempts | ☐ |

## Practice: The Vulnerability Hunt

Go through your current project and check:

1. Is your `JWT_SECRET` in a `.env` file?
2. Do your login routes have a rate limiter?
3. Are you using generic error messages?

If you answered "No" to any of these, now is the time to fix it!

:::info Security Audits
Use tools like `npm audit` frequently. It will scan your project for libraries with known security holes and tell you how to patch them.
:::
66 changes: 65 additions & 1 deletion absolute-beginners/full-stack/authentication/intro.mdx
Original file line number Diff line number Diff line change
@@ -1 +1,65 @@
<ComingSoon />
---
title: "Introduction to Authentication"
sidebar_label: "1. Introduction"
sidebar_position: 1
description: "Learn the fundamental concepts of Authentication vs. Authorization and how security works in web apps."
tags: ["authentication", "authorization", "security", "full-stack development"]
keywords: ["authentication", "authorization", "security", "JWT", "sessions", "hashing", "bcrypt"]
---

In full-stack development, security isn't just an "add-on"—it's the foundation. Before we write any code, we need to understand the two most important concepts in security.

## 1. Authentication vs. Authorization

These terms sound similar, but they do very different things. Think of a **Hotel**:

* **Authentication (AuthN):** This is the **Check-in** process. You show your ID to prove you are who you say you are. The hotel gives you a Key Card.
* *Question:* "Who are you?"
* **Authorization (AuthZ):** This is the **Key Card** itself. Your card lets you into your room (Room 302), but it won't let you into the Manager's office or the Kitchen.
* *Question:* "What are you allowed to do?"

## 2. How it works on the Web

The web is "stateless," meaning the server forgets you the moment a request is finished. To stay logged in, we use a cycle:

1. **Identify:** The user sends their `email` and `password`.
2. **Verify:** The server checks the database (MongoDB/Postgres) to see if the password matches.
3. **Token/Session:** The server sends back a "Proof of Identity" (like a JWT or a Session ID).
4. **Persistence:** The browser stores this proof (usually in a Cookie or LocalStorage) and sends it with every future request.

## 3. Common Auth Methods

At the Hub, we focus on the two industry standards:

### JSON Web Tokens (JWT)
The most popular method for modern MERN apps. The server gives you a "Digital Ticket" (the token). You keep the ticket. Every time you want data, you show the ticket. The server doesn't need to check the database every time; it just validates the ticket.
* **Best for:** Mobile apps, APIs, and Scalable apps.

### Session-Based (Cookies)
The server creates a "file" for you in its memory (or Redis) and gives you an ID number. Your browser saves that ID in a cookie.
* **Best for:** Traditional websites and high-security banking apps.

## 4. The Golden Rules of Security

As you start building auth systems, follow these "Master" principles:

1. **Never store plain-text passwords:** If a hacker steals your database, they shouldn't see "password123." We use **Hashing** (like Bcrypt) to turn passwords into unreadable gibberish.
2. **Always use HTTPS:** Without encryption, anyone on the same Wi-Fi can see the passwords being sent to your server.
3. **Don't reinvent the wheel:** Security is hard. Use trusted libraries like `Passport.js`, `Bcrypt`, or `JsonWebToken`.

## 5. Key Vocabulary

* **Credentials:** Your username and password.
* **Hashing:** A one-way mathematical function that hides passwords.
* **Salt:** Random data added to a password before hashing to make it even harder to crack.
* **Middleware:** The code that stands between a user and a protected route to check if they are logged in.

## Practice: The Security Audit

Look at the apps on your phone (Instagram, WhatsApp, Bank).
* How do they **Authenticate** you? (Password? FaceID? OTP?)
* What are you **Authorized** to see? (Can you see your friend's private messages? Why not?)

:::info
Authentication is where most beginners make mistakes. In the next few lessons, we will build a "Safe" login system step-by-step. **Take your time here—it’s the most important skill in a backend developer's resume.**
:::
105 changes: 104 additions & 1 deletion absolute-beginners/full-stack/authentication/jwt.mdx
Original file line number Diff line number Diff line change
@@ -1 +1,104 @@
<ComingSoon />
---
title: "JWT (JSON Web Tokens) Explained"
sidebar_label: "3. JWT Tokens"
sidebar_position: 3
description: "Learn how to use JSON Web Tokens for stateless authentication in your MERN stack applications."
tags: ["authentication", "JWT", "json web tokens", "security", "full-stack development"]
keywords: ["JWT", "json web tokens", "authentication", "Node.js", "Express", "MongoDB", "PostgreSQL", "jsonwebtoken", "token-based authentication"]
---

A **JWT** is a compact, URL-safe way of representing claims to be transferred between two parties. In simple terms: it is a digital ID card that proves who you are.

## 1. Why use JWT?

In modern web apps (like the ones we build at the Hub), we want our backend to be **Stateless**.
* **Stateful:** The server must remember every logged-in user in its RAM. (Heavy and hard to scale).
* **Stateless (JWT):** The server doesn't remember you. You carry your own "Identity" in your token. The server just verifies the signature on the token.


## 2. Anatomy of a JWT

A JWT looks like a long string of gibberish separated by two dots: `xxxxx.yyyyy.zzzzz`. It has three parts:

1. **Header:** Tells the server what algorithm is used (e.g., HS256).
2. **Payload:** Contains the user data (claims) like `userId` or `username`. **Warning:** Never put passwords here! This part is encoded, not encrypted (anyone can read it).
3. **Signature:** This is the secret sauce. It is a combination of the Header, Payload, and a **Secret Key** known only to your server.

> If a user tries to change the `userId` in the Payload, the **Signature** will no longer match, and the server will reject the token!

## 3. Using JWT in Node.js

We use the `jsonwebtoken` library to handle tokens.

### Installation

```bash
npm install jsonwebtoken
```

### Generating a Token (On Login)

When a user successfully logs in, you "Sign" a token and send it to them.

```javascript title="generateToken.js"
const jwt = require('jsonwebtoken');

const token = jwt.sign(
{ userId: user._id, role: 'student' }, // Payload
process.env.JWT_SECRET, // Your Secret Key
{ expiresIn: '1h' } // Token expires in 1 hour
);

res.json({ token });

```

### Verifying a Token (Middleware)

When the user wants to access a "Protected" route, they send the token in the **Header**. Your server verifies it:

```javascript title="verifyToken.js"
const verifyToken = (req, res, next) => {
const token = req.header('Authorization');

if (!token) return res.status(401).send("Access Denied!");

try {
const verified = jwt.verify(token, process.env.JWT_SECRET);
req.user = verified; // Add user info to the request object
next(); // Move to the actual route
} catch (err) {
res.status(400).send("Invalid Token!");
}
};

```

## 4. Where to store the Token?

As a developer, you have two main choices for where the browser should save the token:

| Location | Security | Complexity |
| --- | --- | --- |
| **LocalStorage** | Vulnerable to XSS (Scripts can steal it). | Very Easy to use. |
| **HttpOnly Cookie** | Immune to XSS. (Best Practice). | Requires more setup. |

At **CodeHarborHub**, we recommend starting with LocalStorage for learning, but moving to **HttpOnly Cookies** for professional projects.

## 5. The "Secret Key" Rule

Your `JWT_SECRET` is the most important piece of data in your backend.

* If someone gets your secret, they can create tokens for **any user** and log in as anyone (even the Admin!).
* **Always** store your secret in a `.env` file and **never** push it to GitHub.

## Practice: The Token Decoder

1. Go to [JWT.io](https://jwt.io/).
2. Paste a token you generated in your code.
3. Look at the "Payload" on the right. Can you see your `userId`?
4. Try changing a single letter in the token string. Watch how the "Signature Invalid" warning appears!

:::info Token Expiration
Always set an expiration time (like `1h` or `7d`). If a token is ever stolen, it won't be useful forever. For "Master" level security, look into **Refresh Tokens** later!
:::
90 changes: 89 additions & 1 deletion absolute-beginners/full-stack/authentication/oauth.mdx
Original file line number Diff line number Diff line change
@@ -1 +1,89 @@
<ComingSoon />
---
title: "OAuth & Social Login"
sidebar_label: "4. OAuth (Social Login)"
sidebar_position: 4
description: "Understand how OAuth works and how to integrate Login with Google using Passport.js."
tags: ["authentication", "oauth", "social login", "passport.js", "google login", "full-stack development"]
keywords: ["oauth", "social login", "passport.js", "google login", "authentication", "Node.js", "Express", "MongoDB", "PostgreSQL"]
---

**OAuth 2.0** is an open-standard authorization protocol that allows a website to access a user's information from another service (like Google or Facebook) without actually seeing the user's password.

## 1. How the OAuth Flow Works

Think of OAuth as a **Valet Key** for a car. You give the valet a special key that lets them park the car, but it won't let them open the trunk or glove box.

1. **The Request:** The user clicks "Login with Google."
2. **The Permission:** Google asks the user, "Do you allow CodeHarborHub to see your email and profile?"
3. **The Code:** Google sends a temporary "Authorization Code" back to your server.
4. **The Exchange:** Your server sends that code + your **Secret Key** to Google to prove it's really you.
5. **The Token:** Google gives your server an `access_token` and the user's profile data.
6. **The Session:** Your server saves the user to the database and logs them in.

## 2. Key Terms You Need to Know

* **Resource Owner:** The User (You).
* **Client:** Your Application (CodeHarborHub).
* **Authorization Server:** The service providing the login (Google/GitHub).
* **Client ID:** A public identifier for your app (given by Google).
* **Client Secret:** A private password for your server (KEEP THIS SECRET!).
* **Callback URL (Redirect URI):** The specific link where Google sends the user after they log in.

## 3. Implementing OAuth with Passport.js

In the Node.js ecosystem, **Passport.js** is the "Master" middleware for authentication. It uses "Strategies" for different providers.

### Installation

```bash
npm install passport passport-google-oauth20 express-session
```

### Basic Configuration

```javascript title="passportConfig.js"
const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth20').Strategy;

passport.use(new GoogleStrategy({
clientID: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
callbackURL: "/auth/google/callback"
},
async (accessToken, refreshToken, profile, done) => {
// 1. Check if user exists in our DB
// 2. If not, create a new user using profile.id and profile.emails[0].value
// 3. Return the user
return done(null, profile);
}
));

```

## 4. The Developer Console Step

You cannot code OAuth without first registering your app with the provider.

1. Go to the [Google Cloud Console](https://console.cloud.google.com/).
2. Create a Project and go to **APIs & Services > Credentials**.
3. Create an **OAuth 2.0 Client ID**.
4. Set the **Authorized Redirect URI** to `http://localhost:5000/auth/google/callback`.
5. Copy your `CLIENT_ID` and `CLIENT_SECRET` to your `.env` file.

## 5. Pros and Cons of OAuth

| Pros | Cons |
| --- | --- |
| **User Experience:** One-click login is faster. | **Dependence:** If Google goes down, users can't log in. |
| **High Security:** No passwords stored on your server. | **Privacy:** Some users don't like sharing data between sites. |
| **Verified Emails:** You know the user's email is real. | **Complexity:** Setting up multiple providers can be tedious. |

## Practice: The Social Audit

1. Go to your Google Account settings under **"Security"**.
2. Find **"Your connections to third-party apps & services"**.
3. See which websites you have given "Valet Keys" to. Notice how you can revoke access at any time!

:::info
When building a real project, always offer a **Hybrid** approach: Let users sign up with an Email/Password (using Bcrypt) OR use Social Login (OAuth). This gives your users the most flexibility!
:::
Loading
Loading