Building Role-based REST API
In this session we are going to implement Token-based Authentication using JSON Web Token (JWT). You will learn the basics of JWT and implementing a role-based REST API. We implement three roles, user, moderator, and system admin. These three roles will have access to their restricted and public content.
- Download the source code Attach:jwt.zip and extract it
- Import it to IntelliJ IDEA
- Add your Postgres Database credentials in
application.properties
file
spring.datasource.url= jdbc:postgresql://localhost:5432/Your_Database spring.datasource.username= Your_Postgres_Username spring.datasource.password= Your_Password
- Run it
- Open
roles
table and insert three roles: ROLE_USER, ROLE_MODERATRO, ROLE_ADMIN
- Open
- Test and check the results using POSTMAN
- Register three users with http://localhost:9091/api/auth/signup API using
POST
method and the following JSON data:
- Register three users with http://localhost:9091/api/auth/signup API using
- User
{ "username": "advera", "email": "user@advera.com", "password": "12345678", "role":["user","user"] }
- Moderator
{ "username": "advera_mod", "email": "mod@advera.com", "password": "12345678", "role":["user","mod"] }
- System Admin
{ "username": "advera_admin", "email": "admin@advera.com", "password": "12345678", "role":["user","admin"] }
- Now try to register another user with
advera_mod
oradvera_admin
and see the response message - Try to register another user with
mod@advera.com
oradmin@advera.com
email address and see the response message
- Now try to register another user with
Access Resources:
- Public Resource:
GET
http://localhost:9091/api/test/all
- Protected Resource without login: * Public Resource:
GET
http://localhost:9091/api/test/user
- Sign in as System Admin
- Use your access token for Authorisation type
Bearer Token
and access the admin restricted content.
Consuming Role-Based API
In this section we present a VueJS app that will utilize the above Role-based REST API. As stated previously, we have three user (User, Moderator, System Admin) and they will see their respective pages when they log in.
- We have a public page that will display "Public Content" provided by the REST API. We don't set any access-token for public visitors.
- We have login and register pages
- We have used
VeeValidate 4
to enable front-end to check form data before sending it to back-end.
- User Authentication
- Download the source code Attach:vue-advera-auth.zip and extract it
- Import it to your IDE (Visual Studio Code)
- Make sure your Role-based REST API service is running
- Open
src/services/auth.service.js
and modify the value ofAPI_URL
to add the URL for Authentication services running on your Spring Boot App - Similarly, open
src/services/user.service.js
and modify the value ofAPI_URL
to add the URL for test services running on your Spring Boot App - Open Terminal and run your application
npm run serve