Building a basic CRUD Todo web app is a great start—but what happens when you want real users with personal task lists and role-based access? In this post, we’ll walk through how we upgraded a simple Spring Boot Todo app by adding:
-
π User Signup and Login
-
π€ Task Ownership per User
-
π‘️ Role-based Access Control (
USER
vsADMIN
)
✅ Original App Recap
Our original Todo app allowed anyone to:
-
Add, edit, delete, and list todos via
/api/todos
-
No login or ownership — todos were public to all users
Great for prototyping, but not secure or scalable for multi-user scenarios.
π What We Added
1. User Entity & Roles
We added a User
entity with fields:
-
id
,username
,password
, androle
(USER
orADMIN
)
We also created an enum Role
to define user roles.
2. Secure Signup and Login Endpoints
We introduced two new endpoints:
-
POST /api/auth/signup
– to create new users -
POST /api/auth/login
– for HTTP Basic Auth (using Spring Security)
User passwords are encrypted with BCrypt and stored securely in the DB.
3. Todo Ownership
Each Todo
now includes a reference to the User
who owns it. We modified the Todo
entity:
1 2 3 | @ManyToOne @JoinColumn(name = "user_id") private User user; |
This lets us associate tasks with users directly.
π§ Updated APIs and Behaviors
π Authentication
-
All endpoints (except
/signup
and/login
) require valid HTTP Basic credentials. -
We use
curl -u username:password
or pass auth headers in frontend requests.
π Task Visibility
-
Normal users can only see their own todos.
-
Admins can see all todos from all users.
π ️ Modified Controllers and Services
We introduced a TodoService
and UserService
to separate logic, and updated the TodoController
to use Authentication
from Spring Security to determine the logged-in user.
π§ͺ Sample Usage (with curl
)
1 2 3 4 5 6 7 8 9 10 11 12 | # Sign up a new user curl -X POST -H "Content-Type: application/json" \ -d "{\"username\":\"user1\",\"password\":\"pass123\"}" \ https://yourdomain.com/api/auth/signup # Create a todo (must be logged in) curl -X POST -u user1:pass123 -H "Content-Type: application/json" \ -d "{\"title\":\"Write blog post\"}" \ https://yourdomain.com/api/todos # List all todos for the current user curl -u user1:pass123 https://yourdomain.com/api/todos |
π§Ό Cleaner JSON Responses
To avoid exposing passwords or internal user data in API responses, we created DTOs:
-
TodoRequest
– for incoming POST/PUT requests -
TodoResponse
– for clean, minimal JSON in responses
π️ Tech Stack
-
Backend: Java Spring Boot
-
Database: MySQL (or PostgreSQL)
-
Security: Spring Security with HTTP Basic Auth
-
Frontend: (Optional) React or cURL for testing
No comments:
Post a Comment