This is a Spring Boot project that demonstrates user authentication and registration using JSON Web Tokens (JWT). The project showcases essential security features such as user login, registration, and secured endpoints.
- User Registration: Users can register with a username and password.
- User Authentication: Registered users can log in and receive a JWT for authentication.
- JWT Authorization: Secure API endpoints using JWTs to allow access to authenticated users only.
- Password Encryption: User passwords are securely stored using BCrypt encryption.
- Exception Handling: Robust error handling for authentication and authorization processes.
- Spring Boot: Simplifies the development of Java applications.
- Spring Security: Provides authentication and authorization features.
- JWT (JSON Web Tokens): Used for securely transmitting information between parties as a JSON object.
- Spring Data JPA: Simplifies data access with JPA.
- H2 Database: In-memory database for quick setup and testing.
- Lombok: Reduces boilerplate code for model objects.
- PostgreSQL: A powerful, open source object-relational database system.
config
: Contains security and JWT configuration classes.auth
: Contains REST controllers for handling user registration and authentication.demo
: Contains a demo controller which displays message when a user has accessed the server successfully after registering and authentication.user
: Contains objects defining users, user repository and roles.
- Java 17 or higher
- Maven
- PostgreSQL (for production use)
-
Clone the repository:
git clone https://github.com/your-username/spring-security-demo.git cd spring-security-demo
-
Create an
application.yml
file insrc/main/resources
with the following content:
jwt:
secret:
key: "your-secret-key"
As well as settings for JPA and the PostgreSQL database, here is an example
spring:
datasource:
url: jdbc:postgresql://localhost:5432/jwt-security
username:
password:
driver-class-name: org.postgresql.Driver
jpa:
hibernate:
ddl-auto: create-drop
show-sql: true
properties:
hibernate:
format_sql: true
database: postgresql
database-platform: org.hibernate.dialect.PostgreSQLDialect
-
Build and run the application:
mvn clean install mvn spring-boot:run
-
Access the application at
http://localhost:8080
.
- User Registration:
POST /api/v1/auth/register
- User Login:
POST /api/v1/auth/authenticate
- Secured Endpoint:
GET /api/v1/democontroller
(Requires JWT)