anawandh / CSA-blog-site

This is a blog site made using template given in AP CSA class. This will be the Experimental lab book for CSA
MIT License
0 stars 0 forks source link

JWT and Backend #19

Open anawandh opened 3 months ago

anawandh commented 3 months ago

Creating the API

I strtedd with simple columns similar to those in Person and slowly changed them to match my needs. The main ones changed are role and classcodes. once this was done I created the APIcontroller file and JPArepository file. Below is the Human.java file.

PersonApiController

The API controller file for the Human class or api had a major change similar to modleinit.java. I had to auto generate a unique class code. Using SecureRandom and BigInteger I created special unique class codes for ONLY "Teachers". Below is a code snippet of the following code -

PersonDetailsService

This was another file that I took from person but added some changes to. One of the major changes is the loadUserByUsername() function. This fucntion gets called eachtime when a request is made with cookies to find the corresponding username from the JWT. So for some error handling and creation of Authorities for specific roles i added some System prints and using getRole and SimpleGrantedAuthority I made the roles of the Human object into an authority that I could use later. Below is the main code segment that was changed -

JWT Implementation

Various changes in files was refrenced or copied from person. the divergence occurs in the role authorities and the changes were the greatest in but not limited to these files:

JWTTokenUtil

This file had major changes to implement roles. We needed to assign the cookie that gets created authorities/roles from what their roles were set to in the database. We add it to the claims that becomes part of the cookie. When the JWT token or cookie is sent back in subsequent api requests we can check them and find their roles and authorities.

Security Config

Using the authorities granted and set up we can allow requests to specfic api endpoints to be accessed only by people have the specfic role

First Test Result:

JWT token generation

Image

Roles and Authorities

Image

Image

Image

Image