> For the complete documentation index, see [llms.txt](https://program.hackyourfuture.dk/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://program.hackyourfuture.dk/course-content/backend/node/week3/session-plan.md).

# Session Plan

## Session outline

* Secure passwords & basic login using the Snippets API (≈40 min)
* Stateless auth with JWT on the Snippets API (≈40 min)
* Session-based auth on the Snippets API (≈40 min)
* Third-party auth explained (5 mins)
* Comparison of auth methods, brief look at DB tokens & API keys, and wrap-up (≈30–35 min)

## Session materials

Examples for the code snippets [present in the module materials examples](https://github.com/HackYourFuture-CPH/program/blob/main/courses/backend/node/module-materials/examples/README.md) can be run with [this Postman collection](https://github.com/HackYourFuture-CPH/program/blob/main/courses/backend/node/module-materials/node.postman_collection.json). Make sure to have it downloaded an up and running.

## Secure passwords & basic login (Snippets API)

**Goal**: Implement secure password storage and a basic login flow for the Snippets API using bcrypt.

* Concept: why plaintext passwords are insecure.
* Introduce hashing and salting with bcrypt.
* Walk through the happy path for `/login`:
  * Look up user by username/email.
  * Compare plaintext password with stored hash using bcrypt.

### Implementation of encrypted password login

* Sketch the table and login route, using the example in [module-materials/examples/auth-login-bcrypt.js](https://github.com/HackYourFuture-CPH/program/blob/main/courses/backend/node/module-materials/examples/auth-login-bcrypt.js).

*See* [*Secure passwords and basic login*](/course-content/backend/node/week3/session-materials/10-auth-db-credentials.md) *for a more detailed walkthrough.*

### Exercise 1 (15–20 min)

* Add at least one user to the `users` table with a hashed password. You can use `token` column.
* Implement `/login` using bcrypt in your own copy of the Snippets API.
* Use Postman to test successful and failing login attempts.

### Why is this approach insecure (5–10 min)

* TODO: show how to break this
* Discuss common mistakes (e.g. sending too much error detail, forgetting to hash passwords).

***

## Stateless auth with JWT

**Goal**: Learn stateless auth with JWT on top of the secure login flow, and protect key Snippets API endpoints.

* Concept: self-contained tokens with claims; no DB lookup needed per request.
* Trade-offs: fast and scalable, but harder to revoke.
* Show the high-level flow:
  * After successful bcrypt-based login, issue a JWT.
  * Client includes the token in the `Authorization` header.
  * Middleware verifies the token and attaches user info to `req.user`.

### Implementation of JWT token in middleware

* Use the JWT login and middleware flow from [module-materials/examples/auth-jwt.js](https://github.com/HackYourFuture-CPH/program/blob/main/courses/backend/node/module-materials/examples/auth-jwt.js) as a reference while coding in the Snippets API.

*See* [*Stateless authentication with JWT*](/course-content/backend/node/week3/session-materials/12-auth-jwt.md) *for detailed steps and examples.*

### Exercise 2 (15–20 min)

* Protect at least two Snippets API endpoints (e.g. `POST /api/snippets`, `DELETE /api/snippets/:id`) using JWT middleware.
* Add token expiration and handle expired tokens gracefully in responses.
* Try to tamper with the token payload and see what happens.

### Using JWT in Postman

* Run through a full Postman flow together.
* In Postman, add JWT as Bearer Token (unique token after login) or just JWT auth based on secret. Show the difference between authorised & authenticated reponse.

***

## Session-based authentication

**Goal**: Implement session-based authentication using cookies and compare it to JWT for the Snippets API.

* Concept: server-side sessions, session IDs in cookies, and typical use cases.
* Contrast with JWT: stateful vs stateless, revocation, and infrastructure needs.

### Implementation of session based auth

* Use the session-based login and middleware flow from [module-materials/examples/auth-sessions.js](https://github.com/HackYourFuture-CPH/program/blob/main/courses/backend/node/module-materials/examples/auth-sessions.js) as a reference while integrating sessions into the Snippets API.

*See* [*Session-based authentication*](/course-content/backend/node/week3/session-materials/13-auth-sessions.md) *for detailed guidance.*

### Exercise 3 (15–20 min)

* Protect at least one Snippets API route using session-based middleware.
* Implement logout and verify that access is denied after logging out.

### How are sessions different than JWT (5–10 min)

* Compare the experience of working with sessions vs JWT.
* Discuss scaling concerns (sticky sessions, shared stores) at a high level.

***

## Third-party authentication (Firebase, Supabase, Auth0, etc.)

**Goal**: Understand what managed authentication providers are, what problems they solve, and how they relate to the methods used in this session.

* Explain what third-party auth providers are:
  * Hosted “auth as a service” platforms such as Firebase Auth, Supabase Auth, Auth0, or AWS Cognito.
  * They manage user accounts, password reset, social logins, multi-factor auth, and often sessions/tokens for you.
* Discuss **benefits**:
  * Offload security-sensitive behaviour (password storage, brute-force protection, MFA) to specialists.
  * Faster development: SDKs, UI widgets, and ready-made flows.
  * Built-in support for social/enterprise logins that would be complex to implement yourself.
* Discuss **trade-offs**:
  * Vendor lock-in and data model coupling.
  * Less flexibility for unusual requirements.
  * Cost and dependency on an external service for uptime and SLAs.
* Connect to what trainees have built:
  * Under the hood, these providers typically use the same concepts:
    * Secure password hashing.
    * JWTs or opaque tokens.
    * Sessions/cookies and refresh tokens.
  * In a Node backend, you usually **verify** a token issued by the provider in middleware and then treat the request as authenticated if verification succeeds.

***

## Comparison, DB tokens & API keys overview, and wrap-up

**Goal**: Compare the different auth approaches, introduce DB-stored tokens and API keys conceptually, and connect to the assignment.

### Comparing auth methods (10–15 min)

* Revisit the methods you have seen:
  * Secure passwords (with bcrypt) and basic login.
  * JWT-based stateless auth.
  * Session-based auth.
* Introduce **database-stored tokens**:
  * Tokens stored in a `tokens` table, lookup on each request.
  * Easier revocation, but requires a DB call every time.
* Introduce **API keys**:
  * Simple secret keys for machine-to-machine communication.
  * Not ideal as the only method for user authentication.
* Show a comparison table summarising trade-offs:

| Method                 | DB Lookup | Revocable | Scalable | Typical use case                                  |
| ---------------------- | --------- | --------- | -------- | ------------------------------------------------- |
| Secure credentials     | Yes       | No        | No       | Legacy / simple systems                           |
| Database tokens        | Yes       | Yes       | No       | Small apps                                        |
| JWT                    | No        | Not easy  | Yes      | SPAs, mobile apps                                 |
| Sessions               | Yes       | Yes       | Depends  | Traditional web apps                              |
| API keys               | No        | Not easy  | Yes      | Machine-to-machine                                |
| Third-party auth (IdP) | Depends   | Yes       | Yes      | SaaS, bigger products, "don't have time for this" |

*See* [*Database-stored tokens*](/course-content/backend/node/week3/session-materials/11-auth-db-tokens.md) *and* [*API keys*](/course-content/backend/node/week3/session-materials/14-auth-api-keys.md) *for additional details and examples.*

### Final wrap-up

* Reiterate best practices:
  * [Always use HTTPS](https://www.freecodecamp.org/news/http-and-everything-you-need-to-know-about-it).
  * Always hash passwords (bcrypt or similar).
  * Store tokens securely (e.g. HttpOnly cookies for web clients).
  * Prefer short-lived tokens and consider refresh tokens where appropriate.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://program.hackyourfuture.dk/course-content/backend/node/week3/session-plan.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
