JWTUtil
JWTAuthFilter
JWTAuthEntryPoint
CustomUserDetailsService
SecurityConfig
Open src/main/resources/application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/testdb?createDatabaseIfNotExist=true
spring.datasource.username= your_username
spring.datasource.password= your_password
#properties for MySQL
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.format_sql=true
#JWT Token
#base64(256 bits)
spring.security.jwt.secret=6k9YeP6LdZf27PaMM2PGRbM11XqAfQsHcFQt2uLAV/U=
#1min
spring.security.jwt.expirationMs=60000
All users registered via the registration endpoint are assigned the 'user' role by default. To assign admin privileges, please manually insert the admin credentials into the register table.Password - BCryptEncoded
INSERT INTO register (reg_id,email, first_name, last_name , password , role)
VALUES (1,'admin@gmail.com', 'admin','A','$2a$10$uBwznt.UGsEY1zahgdYyguDSIyME085OT15fjTz5I4HYtPwmPokEO','ADMIN');
Ensure that the employee table contains data to retrieve information when accessing the /admin/emplist endpoint. You can also use Postman to insert data.
INSERT INTO employee (empId, empName, dept, gmail, phno, dob, gender, salary, joinDate) VALUES
(1, 'Michael Johnson', 'Sales', 'michael.johnson@gmail.com', '8786543210', '1988-11-11', 'male', 80000, '2020-12-01');
-
Make sure you have Java 17 or 21 and Maven installed
-
Fork this repository and clone it
$ git clone https://github.com/<your-user>/SpringSecurity6-JWT_RBAC-MYSqlConnection
- Navigate into the folder
$ cd SpringSecurity6-JWT_RBAC-MYSqlConnection
- Install dependencies
$ mvn install
- Run the project
$ mvn spring-boot:run
-
Open Postman
-
Make a GET request to
/admin/emplist
to check you're not authenticated. You should receive a response with a401
with anUnauthorized
message since you haven't set your valid JWT token yet -
Make a POST request to
/signin
with the default admin user we programatically created to get a valid JWT token
$ POST 'http://localhost:8080/signin
#with body
{
"username":"admin@gmail.com",
"password":"admin@123"
}
- Add the JWT token as a Header parameter and make the initial GET request to
/admin/emplist
again
$ GET http://localhost:8080/admin/emplist -H 'Authorization: Bearer <JWT_TOKEN>'
- And that's it, congrats! You should get a similar response to this one, meaning that you're now authenticated
{
"empId": 1,
"empName": "Michael Johnson",
"dept": "Sales",
"gmail": "michael.johnson@gmail.com",
"phno": "8786543210",
"dob": "1988-11-11T00:00:00.000+00:00",
"gender": "male",
"salary": 80000,
"joinDate": "2020-12-01T00:00:00.000+00:00"
}
Check out my LinkedIn profile for a demo video of this project.
Happy Coding!ππ¨βπ»π©βπ»