Skip to content

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.

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()

“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.”

  • Configure Swagger to accept a Bearer token for testing
  • Get current user info from the token in an endpoint
  • JWT internals (signing, claims structure)
  • Token expiration handling on the client side
  • Password reset flow

Add user registration and login to the Books API, and protect write operations.

  1. Create a User entity with Id, Username, Email, PasswordHash
  2. Add DbSet<User> to BooksDb and run a new migration
  3. Install the BCrypt.Net-Next NuGet package
  4. Build POST /auth/register: hash password with BCrypt, check for duplicate emails, save user
  5. Build POST /auth/login: find user by email, verify password, return JWT token
  6. Install Microsoft.AspNetCore.Authentication.JwtBearer
  7. Add JWT settings to appsettings.json (Key, Issuer, Audience)
  8. Add JWT authentication middleware to Program.cs
  9. Add .RequireAuthorization() to POST, PUT, and DELETE /books
  10. Leave GET /books and GET /books/{id} public
  11. Configure Swagger to include an “Authorize” button for Bearer tokens
  12. Test the full flow: register → login → copy token → paste into Swagger → create a book
  • Why passwords must never be stored as plain text
  • BCrypt.HashPassword() and BCrypt.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

Users can register and login. Write endpoints require a valid JWT token.


Week 5: Validation | Back to Overview | Week 7: Testing