Week 6: Authentication with JWT
Add user registration and login to the API. Protect write endpoints so only logged-in users can create, update, and delete books.
Essential (80% of time)
Section titled “Essential (80% of time)”Core skills:
- Create a User entity with a hashed password
- Build a registration endpoint
- Build a login endpoint that returns a JWT token
- Configure JWT authentication middleware
- Protect endpoints with
.RequireAuthorization()
Key resources
Section titled “Key resources”LLM prompts
Section titled “LLM prompts”“Create a User entity with Id, Username, Email, PasswordHash. Show me the EF Core migration.”
“Build a registration endpoint: accept email and password, hash password with BCrypt, save to database. Handle duplicate emails.”
“Build a login endpoint: verify password with BCrypt, return a JWT token on success.”
“Show me minimal JWT configuration in Program.cs. What NuGet packages do I need?”
“Protect my POST /books endpoint so only logged-in users can create books.”
Brief (20% of time)
Section titled “Brief (20% of time)”- Configure Swagger to accept a Bearer token for testing
- Get current user info from the token in an endpoint
Optional (skip if needed)
Section titled “Optional (skip if needed)”- JWT internals (signing, claims structure)
- Token expiration handling on the client side
- Password reset flow
Practical project
Section titled “Practical project”Add user registration and login to the Books API, and protect write operations.
Learning activities
Section titled “Learning activities”- Create a
Userentity with Id, Username, Email, PasswordHash - Add
DbSet<User>to BooksDb and run a new migration - Install the
BCrypt.Net-NextNuGet package - Build POST /auth/register: hash password with BCrypt, check for duplicate emails, save user
- Build POST /auth/login: find user by email, verify password, return JWT token
- Install
Microsoft.AspNetCore.Authentication.JwtBearer - Add JWT settings to appsettings.json (Key, Issuer, Audience)
- Add JWT authentication middleware to Program.cs
- Add
.RequireAuthorization()to POST, PUT, and DELETE /books - Leave GET /books and GET /books/{id} public
- Configure Swagger to include an “Authorize” button for Bearer tokens
- Test the full flow: register → login → copy token → paste into Swagger → create a book
Key concepts to master
Section titled “Key concepts to master”- Why passwords must never be stored as plain text
BCrypt.HashPassword()andBCrypt.Verify()- What a JWT token is — a signed, self-contained credential
- JWT middleware setup in Program.cs
.RequireAuthorization()to protect individual endpoints- The difference between public and protected endpoints
Deliverable
Section titled “Deliverable”Users can register and login. Write endpoints require a valid JWT token.