This project demonstrates how to implement JWT (JSON Web Token) authentication using Spring Boot. It includes user registration, login, and securing endpoints using JWT tokens.
- Spring Boot
- Spring Security
- JWT (JSON Web Token)
- Hibernate (JPA)
- H2 Database (for simplicity)
- Maven
-
Clone the repository:
git clone https://github.com/hilmiugurpolat/JWT-Authentication-with-Spring-Boot.git cd JWT-Authentication-with-Spring-Boot
-
Build the project:
mvn clean install
-
Run the application:
mvn spring-boot:run
The application will start on http://localhost:8080
.
-
URL:
/api/auth/register
-
Method:
POST
-
Request Body:
{ "email": "example@example.com", "username": "exampleuser", "password": "password123" }
-
Response:
{ "message": "User registered successfully" }
-
URL:
/api/auth/login
-
Method:
POST
-
Request Body:
{ "username": "exampleuser", "password": "password123" }
-
Response:
{ "token": "<JWT_TOKEN>" }
-
URL:
/api/test
-
Method:
GET
-
Headers:
- Key:
Authorization
- Value:
Bearer <JWT_TOKEN>
- Key:
-
Response:
{ "message": "Access granted!" }
The secret key used to sign the JWT is defined in the JwtUtil
class:
private String SECRET_KEY = "secret";