Script Valley
Express.js: APIs and Middleware
Authentication and Authorization/Assessment

Practice & Assessment

Test your understanding of Authentication and Authorization

Multiple Choice Questions

5
1

What does `jwt.verify()` check when validating a token?

2

What HTTP status should be returned when a valid JWT user tries to access a resource they don't have permission for?

3

Why must `require('dotenv').config()` be the first line in app.js?

4

Why does bcrypt use a salt when hashing passwords?

5

What is the correct format for sending a JWT in an HTTP request?

Coding Challenges

1
1

Implement Auth Middleware with RBAC

Build an Express app with user data in an in-memory array (each user has id, email, hashedPassword using bcryptjs, role: 'user' or 'admin'). Implement POST /auth/register (hash password, return user without password), POST /auth/login (verify with bcrypt.compare, return JWT), GET /profile (authenticate middleware required, returns req.user), GET /admin/users (authenticate + authorize('admin') required, returns all users). Inputs: JSON body for register/login. Outputs: { token } on login, user object on profile. Time estimate: 30 minutes.

Medium

Mini Project

1

Authenticated Blog API

Build a blog post API with full authentication. Schema: users (id, email, hashedPassword, role: user/admin), posts (id, title, content, authorId, createdAt). Implement: POST /auth/register, POST /auth/login (returns JWT), GET /posts (public), GET /posts/:id (public), POST /posts (authenticated, sets authorId from req.user), PUT /posts/:id (authenticate + ownerOrAdmin check), DELETE /posts/:id (authenticate + ownerOrAdmin check), GET /admin/posts (authenticate + authorize('admin')). Use bcryptjs for passwords, jsonwebtoken for tokens, dotenv for JWT_SECRET. All secrets from process.env.

Medium