🎙 Free live masterclass · Sun, 29 Nov, 7:00 pm IST · Java Full Stack roadmap Register free →
Skills101

Blog API with JWT login

A multi-user blog backend: sign up, log in for a JWT, write posts and comments, with roles for admins.

Intermediate⏱ 12–16 hoursđŸĒœ 7 stepsSpring BootSpring SecurityJWTMySQL

What you'll learn

  • ◆Spring Security filter chain
  • ◆Password hashing with BCrypt
  • ◆JWT access tokens and role-based access

What you'll build

  • ✓Register and login (returns JWT)
  • ✓Posts with title, body, tags; only the author can edit
  • ✓Comments on posts
  • ✓ADMIN role can delete anything

Step-by-step guide

  1. 1

    Entities

    User(id, email, passwordHash, role), Post(id, title, body, author, createdAt), Comment(id, post, author, text). Map relations with @ManyToOne.

  2. 2

    Register

    Hash the password with BCryptPasswordEncoder and save; reject duplicate emails.

  3. 3

    Login and JWT

    Authenticate with AuthenticationManager; issue a signed token with a library such as jjwt (subject = user id, short expiry).

  4. 4

    JWT filter

    A OncePerRequestFilter reads "Authorization: Bearer ...", validates the token and sets the SecurityContext.

  5. 5

    Security rules

    In a SecurityFilterChain bean: permit /api/auth/** and GET /api/posts/**, require auth for the rest, stateless sessions, CSRF off for this token API.

  6. 6

    Ownership checks

    In PostService, allow update/delete only if post.author.id equals the current user or the user is ADMIN (or use @PreAuthorize).

  7. 7

    Pagination and tests

    Page posts with Pageable; test secured endpoints with @WithMockUser and MockMvc.

🚀 Make it stand out

  • +Refresh tokens
  • +Upload a cover image
  • +Full-text search on posts