How To Build Web Service Using Spring Boot 2x
Do you want to create a web-service application using spring boot? Then please check this architecture template. Let it be a kick for your starting.
Join the DZone community and get the full member experience.Join For Free
- MVC Architecture
- JWT Based Authentication
- Spring Data (JPA)
- Application User Password Encryption
- DB password Encryption.
- SQL Server
- Swagger For API Doc
- Application Source code.
- SQl script of Data Base along with key data.
- DB.txt file contains the DB config details.
- Postman JSON script to test all web-services.
- Install JDK 11 or latest.
- Clone the Project repository into local.
- Git Url : https://github.com/VishnuViswam/sample-web-service.git
- Install SQL server 2012.
- Create application DB and user
- Insert the DB key data.
- Add the decoding key of the database password into the system variables. It is present in DB.txt file.
- Sometimes we may need to restart the windows to pick up the updated system variables.
- Run the project source code.
- To call the web-services, import provided postman JSON scripts into the postman client application.
Each Web-services of application will be declared in the controller layer.
- @RequestMapping("/api/v1/user") annotation used to mention the category of web service.
- @RestController annotation will configure the class to receive the rest-full web service call.
- @PostMapping() annotation will decide the HTTP request type.
- consumes & consumes tags will decide the content type of the HTTP request and response.
From this "controller layer" API request will be taken to the service layer. All business logic will be handled here, then it will talk with the database using JPA.
- All interaction of the application with the database will handle by the JPA library.
- JPA will have Entity class and corresponding Repository interface for all logical objects in the application.
- Other JPA configurations will be done in application.properties named file.
- Database name, connection URL, user credentials all these kinds of values are configured in the application.properties file.
Database Password Encryption
- Application database password will be encrypted using __Jasypt __ library with the help of a encryption key.
- This encryption key need to add in the system variables
- Above is the line in the property file, which help the application to decrypt the password using the key which is previously added in the system variables.
- We also provide @EnableEncryptableProperties annotation in the application main class to let the application know about this database password encryption configuration.
- We implemented JSON Web Token-based authentication with the help of spring security.
- Upon success logged in of a user, we will create two tokens (accessToken && refreshToken) and send back to the client.
- accessToken will be created using a privet key, expiry time (1 hr), user id and role name.
- refreshToken will be created using a privet key , expiry time (24 hr), user id and role name.
- After success login each API request needs to have this accessToken in the header under Authorization key.
- A "bearer" named key should be attached at the starting of the access token like follows.
- "bearer accessToken"
- Access token will keep monitor in every web-service request.
- If the validity of the access token expires we revert the request with 401 HTTP status.
- At that moment web-service user (client) needs to call access token renewal request using the refresh token.
- Then we will check the validity of refresh token, if it is not expired we will give a new access token and refresh token.
- Client can continue using these new tokens.
- If the validity of the refresh token also expired we ask them to re login using username and password.
- In the above code userLoginService named method will check the credentials of the user and providing tokens if it is valid.
- CreateNewAccessTokenUsingRefreshToken named method will create the new access token and refresh token upon the success refresh token validation.
- This configuration will enable the spring security module using @EnableWebSecurity AND @EnableGlobalMethodSecurity(prePostEnabled = true) named annotations.
- Here we will inject then JWT filter into the HTTP request of the system.
- Here in the above class JwtAuthenticationTokenFilter() named method will filter all incoming web-service requests who have "api" named keyword in the URL.
- All filtered web-service requests will reach attemptAuthentication named method.
- And we can do all our business logic in this method.
- All passwords of the users in this application will be encrypted for security using BCrypt.
- Here encode named method is used to encrypt the password.
- And matches named method is using to cross-check the provided password and actual password of the user.
- We have one XML file to configure the Log4j2 named by log4j2.xml.
- To log information from each class, we need to inject the respective class to the Log4j2.
- Above code snippet shows how we inject the class into the logger.
- Following are the basic methods to log the information.
- API doc has an important role in the web-service application.
- Previously we used to create API doc using any static excel documents
- This library will help us to create the API doc using some annotations inside the application.
- These are the libraries we used in the pom file to integrate Swagger.
- We need to do some configurations in the applications to enable the API doc.
- As we can see in the above class need to add some basic information about our project.
- We need to tell swagger from which class needs to create API docs, and that is configured under .apis(RequestHandlerSelectors.withClassAnnotation,(RestController.class)) named line.
- Swagger API doc will be accessible from http://localhost:8080/SampleWebservice/apidoc this link.
- We can find 2 Postman JSON script in the repository. Please import both of them into the Postman client application.
- Execute the login web-service request at first. Then execute the rest of the web-services.
Opinions expressed by DZone contributors are their own.