Spring Security
Introduction

Spring Security just like a filter, it will pre-process between the user request and the controller
The secured api end point will be cover by a spring security filter. In order to access the secured api end point, user is required to login with their correct role to pass the authorization which is a kind of filter
Pre-Action
Install the maven dependency
Configuration
To declare the data source of user
To register the custom filter for authorization as a bean
To register the authentication manager which act as an entry point of the login request as a bean
To register the password encoder to do hashing for password as a bean
To allow CORS and disable CSRF (Cross-site request forgery)
To declare which API end point would be secured
To declare handling method for failed authentication not access right issue
To allow all API end point can be cross-origin
Authorization Filter
To declare the logic of authentication which is a filter and the method of obtaining token from header of request
Obtain the token from header, then validate the token
If the token is null or not valid , the handler of failed authentication will be triggered to return the error response
If the token is valid, the authorization will be set
Handler of failed authentication
To declare the handling and the return response for failed authentication including user failed to login or access secured API end point without login
To declare the handling and the return response for the issue that user have not enough access right to access secured API end point , even though he is logged in
User Details
User details is the data modal that will be returned if authentication is passed
Since the default user detail only include username , password and role
In order to extend the modal ( in this case, also include email), we customize the modal
User Details Service
User details service is to declare how to get the user details
From here, we declare the method that get the user detail by searching table on database by using username
Json Web Token Utils
To declare the method of generating token based on the user details from authentication
To declare the method of obtaining username from token
To do validate the token whether it is generated from our application or not
Enum
Declare the type of role
Modal
ORM
Declare the modal mapped with table of database
Request
Response
Exception and Exception handler
Repository
Controller
Service
Flow
Login

Post username and password
Put it into UsernamePasswordAuthToken
Do authentication by authentication manager which is help by user details service and password encoder
If failed , go to error handler
If success, return token
Access Secured Api End Point

User make a request
Enter custom authentication filter which is a single execution for each request to api
Extract token from header of request
Validate the token
If failed, go to error handler
If success, access the API end point
Reference
Last updated
Was this helpful?
