This repository offers a template for a Spring Boot application that leverages JSON Web Token (JWT) for user authentication and authorization with role-based access control. It integrates Spring Security to safeguard RESTful APIs and facilitate an implicit authentication flow.
Create an .env
file in the root directory of the project and add the following environment variables:
MYSQL_DATABASE=<database_name>
MYSQL_ROOT_PASSWORD=<root_password>
MYSQL_USER=<mysql_user>
MYSQL_PASSWORD=<mysql_user_password>
SERVER_PORT=8080
DATASOURCE_URL=jdbc:mysql://localhost:3306/<database_name>
DATASOURCE_USERNAME=<mysql_user>
DATASOURCE_PASSWORD=<mysql_user_password>
JWT_SECRET=<jwt_secret_key>
-
Initialize the MySQL database:
docker compose up -d
-
Build and run the application:
./gradlew build ./gradlew bootRun
The application setup includes an initial admin user with credentials:
username: admin@test.com
password: adminpassword
Base URL:
http://localhost:8080/api/v1
The following endpoints are available post-deployment:
- Sign Up:
/auth/signup
- Sign In:
/auth/signin
- Refresh Token:
/auth/refresh
- Sample Admin Endpoint:
/admin
(requires 'ADMIN' role) - Sample User Endpoint:
/user
(requires 'USER' role)
Use the JWT token returned by the /auth/signin
endpoint to access the
/admin
and /user
endpoints.
Authenticate by providing the JWT obtained from /auth/signin. Refresh tokens can be acquired via /auth/refresh.
Endpoints for authentication services:
-
POST
/auth/signup
: Register a new user.{ "firstName": "<firstName>", "lastName": "<lastName>", "email": "<email>", "password": "<password>" }
-
POST
/auth/signin
: Login and receive an access token.{ "email": "<email>", "password": "<password>" }
Response:
{ "token": "<token>", "refreshToken": "<refreshToken>" }
-
POST
/auth/refresh
: Refresh an access token.{ "token": "<refreshToken>" }
Response:
{ "token": "<token>", "refreshToken": "<refreshToken>" }
Access the OpenAPI documentation at:
http://localhost:8080/swagger-ui/index.html?configUrl=/v3/api-docs/swagger-config`
For unit testing, run the following command:
./gradlew test
For API testing, a Postman collection is provided: Postman Collection
Ensure that the following environment variables are set: Environment
Pre-request scripts are provided to automate the process of obtaining a JWT token and refreshing it.
This project is licensed under the MIT License.