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.
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
Entities
User(id, email, passwordHash, role), Post(id, title, body, author, createdAt), Comment(id, post, author, text). Map relations with @ManyToOne.
- 2
Register
Hash the password with BCryptPasswordEncoder and save; reject duplicate emails.
- 3
Login and JWT
Authenticate with AuthenticationManager; issue a signed token with a library such as jjwt (subject = user id, short expiry).
- 4
JWT filter
A OncePerRequestFilter reads "Authorization: Bearer ...", validates the token and sets the SecurityContext.
- 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
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
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