Skip to content

SirajChaudhary/spring-boot-jwt-example

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Spring Boot JWT Example

A Spring Boot 3 example project demonstrating JWT-based authentication with role-based authorization, secured and public APIs, MySQL persistence, and Swagger/OpenAPI documentation.


Table of Contents


Features

  • JWT-based authentication (HS256)
  • Role-based authorization (ADMIN and USER)
  • Public and secured APIs
  • MySQL persistence for users and employees
  • Swagger UI for API testing and documentation
  • Password hashing with BCrypt
  • Register API now accepts roles and returns JWT upon registration

Tech Stack

  • Spring Boot: 3.5.6
  • Spring Security
  • Spring Data JPA
  • MySQL 8
  • JJWT: 0.13.0
  • Swagger/OpenAPI: springdoc-openapi-starter-webmvc-ui 2.8.13
  • Lombok for reducing boilerplate code

Database Setup

Run the following SQL scripts to create the database, tables, and seed initial data:

CREATE DATABASE IF NOT EXISTS spring_jwt_example_db;
USE spring_jwt_example_db;

CREATE TABLE users (
  id BIGINT AUTO_INCREMENT PRIMARY KEY,
  username VARCHAR(100) NOT NULL UNIQUE,
  password VARCHAR(255) NOT NULL,
  roles VARCHAR(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE employees (
  id BIGINT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(100) NOT NULL,
  position VARCHAR(100),
  salary DECIMAL(15,2)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Seed initial users and employees
-- Passwords are BCrypt hashes for plaintext 'password'
INSERT INTO users (username, password, roles) VALUES
('prasad', '$2a$10$4K1d2KNxm6XcpYsENft2sOsMgqUKBoT2AptzmGksJkysfhUuHKd8K', 'ADMIN'),
('siraj', '$2a$10$HlIx8Tcg2K1E83ohj1/bTeqz1B.nNFj/AJV09WNrBOMHZKb2tDYkK', 'USER');

INSERT INTO employees (name, position, salary) VALUES
('Sachin Tendulkar', 'Manager', 90000.00),
('Ricky Ponting', 'Developer', 75000.00);

Note: Passwords are BCrypt hashes. Use strong passwords in production.


Project Structure

src/main/java/com/example/
├── config/
│   ├── SecurityConfig.java
│   └── SwaggerConfig.java
├── controller/
│   ├── AuthenticationController.java
│   ├── EmployeeController.java
│   └── PublicController.java
├── dto/
│   ├── AuthRequest.java
│   ├── AuthResponse.java
│   └── RegisterRequest.java   <-- includes username, password, roles
├── entity/
│   ├── User.java
│   └── Employee.java
├── exception/
│   └── GlobalExceptionHandler.java
├── repository/
│   ├── UserRepository.java
│   └── EmployeeRepository.java
├── security/
│   ├── JwtService.java
│   └── JwtAuthenticationFilter.java
├── service/
│   ├── UserService.java
│   ├── AuthenticationService.java
│   └── EmployeeService.java
└── SpringBootJwtExampleApplication.java

src/main/resources/
├── db/
│   └── script.sql
└── static/

Application Properties

spring.application.name=spring-boot-jwt-example
server.port=8080

# MySQL configuration
spring.datasource.url=jdbc:mysql://localhost:3306/spring_jwt_example_db?useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=Siraj123
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

# JPA
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect

# JWT
app.jwt.secret=ReplaceWithAStrongSecretKeyAtLeast32BytesLong!!
app.jwt.expiration-ms=3600000

Running the Application

  1. Clone the repository.
  2. Ensure MySQL is running and the database is created.
  3. Configure credentials in application.properties.
  4. Build and run:
mvn clean install
mvn spring-boot:run

The application will run on http://localhost:8080.


Swagger Documentation

Swagger UI is available at:

http://localhost:8080/swagger-ui/index.html

OpenAPI JSON:

http://localhost:8080/v3/api-docs

Using JWT in Swagger:

  1. Click the Authorize button in Swagger UI.
  2. Enter the JWT token as:
Bearer <JWT_TOKEN>
  1. Click Authorize → Close.

Sample Users

Username Password Roles
prasad password ADMIN
siraj password USER
  • passwords for these sample users we kept 12345 (bcrypt value)

API Endpoints

Public

  • POST /api/v1/auth/login – Login and receive JWT
  • POST /api/v1/auth/register – Register a new user (with roles) and receive JWT
  • GET /api/v1/public/hello – Public endpoint (No need of JWT)

Secured (JWT Required)

  • GET /api/v1/employees – Get all employees
  • GET /api/v1/employees/{id} – Get employee by ID
  • POST /api/v1/employees – Create employee (ADMIN only)
  • PUT /api/v1/employees/{id} – Update employee (ADMIN only)
  • DELETE /api/v1/employees/{id} – Delete employee (ADMIN only)

Use the Authorization: Bearer <token> header for secured endpoints.


Notes

  • JWT secret must be at least 32 characters for HS256.
  • Roles are passed directly during registration (e.g., "ADMIN", "USER").
  • Roles in the database are stored without ROLE_ prefix; UserService maps them to Spring Security roles.
  • Swagger endpoints (/swagger-ui/** and /v3/api-docs/**) are public for testing.
  • For production configure HTTPS.

About

A Spring Boot + Spring Security example showing how to issue and validate JWT (JSON Web Tokens), implement role-based access control (RBAC), and secure REST endpoints using stateless authentication.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages