A Spring Boot application that provides JWT-based authentication with MongoDB as the database.
- User registration and login
- JWT token generation and validation
- Password encryption using BCrypt
- MongoDB integration
- Input validation
- Protected endpoints
- Java 21
- MongoDB running on localhost:27017
- Maven
-
Start MongoDB
# Make sure MongoDB is running on localhost:27017 mongod -
Run the application
./mvnw spring-boot:run
-
The application will start on port 8080
POST /auth/register
Content-Type: application/json
{
"username": "testuser",
"email": "test@example.com",
"password": "password123"
}POST /auth/login
Content-Type: application/json
{
"username": "testuser",
"password": "password123"
}Response:
{
"token": "eyJhbGciOiJIUzI1NiJ9..."
}GET /auth/testGET /auth/protected
Authorization: Bearer <your-jwt-token>The application uses the following configuration in application.properties:
- MongoDB URI:
mongodb://localhost:27017/userdb - JWT Secret: Base64 encoded secret key
- JWT Expiration: 1 hour (3600000 ms)
- Passwords are encrypted using BCrypt
- JWT tokens are signed with HS256 algorithm
- Protected endpoints require valid JWT token in Authorization header
- Input validation for user registration
The application creates a userdb database in MongoDB with a users collection.
User document structure:
{
"_id": "ObjectId",
"username": "string (unique)",
"email": "string (unique)",
"password": "string (encrypted)",
"role": "string (default: USER)"
}- Register a user:
curl -X POST http://localhost:8080/auth/register \
-H "Content-Type: application/json" \
-d '{"username":"testuser","email":"test@example.com","password":"password123"}'- Login:
curl -X POST http://localhost:8080/auth/login \
-H "Content-Type: application/json" \
-d '{"username":"testuser","password":"password123"}'- Access protected endpoint:
curl -X GET http://localhost:8080/auth/protected \
-H "Authorization: Bearer YOUR_JWT_TOKEN_HERE"