How To Build Web Service Using Spring Boot 2.x
Do you want to create a web-service application using Spring Boot? Check out this architecture template and let it be a kick for your starting.
Join the DZone community and get the full member experience.
Join For FreeArchitecture Contains
- MVC Architecture
- JWT Based Authentication
- Spring Data (JPA)
- Application User Password Encryption
- DB password Encryption.
- SQL Server
- Slf4j
- Swagger For API Doc
Repository Contains
- 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.
Steps to Run Applications
- Install JDK 11 or the latest version.
- 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 the 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.
About Project Configurations
Web-Service Declaration
Each Web-services of the application will be declared in the controller layer.
Example
@RequestMapping("/api/v1/user")
@RestController
@Validated
public class UserController {
private static final Logger logger = LoggerFactory.getLogger(UserController.class);
@Autowired
private GeneralServices generalServices;
@Autowired
private UserService userService;
/**
* Web service to create new user
*
* @param httpServletRequest
* @param user
* @return
*/
@PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> createUser(HttpServletRequest httpServletRequest,
@Valid @RequestBody UserCreateModel user) {
logger.debug("<--- Service to save new user request : received --->");
ApiSuccessResponse apiResponse = userService.createUser(user, generalServices.getApiRequestedUserId(httpServletRequest));
logger.debug("<--- Service to save new user response : given --->");
return ResponseEntity.status(HttpStatus.CREATED).body(apiResponse);
}
}
- @RequestMapping("/api/v1/user") annotation is 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 requests will be taken to the service layer. All business logic will be handled here, then it will talk with the database using JPA.
Common Error Handling
Whenever an exception happens, it will throw from the respective classes and be handled in the "CommonExceptionHandlingController." We have to handle this separately for each type of exception. This function is performed with the help of "ControllerAdvice" named annotation.
Example
@ControllerAdvice
public class CommonExceptionHandlingController extends ResponseEntityExceptionHandler {
private static final Logger logger =
LoggerFactory.getLogger(CommonExceptionHandlingController.class);
@Override
protected ResponseEntity<Object> handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException httpRequestMethodNotSupportedException,
HttpHeaders headers, HttpStatus status, WebRequest request) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(new ApiErrorResponse(Constants.WRONG_HTTP_METHOD,
Constants.WRONG_HTTP_METHOD_ERROR_MESSAGE, Calendar.getInstance().getTimeInMillis()));
}
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException methodArgumentNotValidException,
HttpHeaders headers, HttpStatus status, WebRequest request) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ApiErrorResponse(Constants.MANDATORY_FIELDS_ARE_NOT_PRESENT_CODE,
Constants.MANDATORY_FIELDS_ARE_NOT_PRESENT_ERROR_MESSAGE, Calendar.getInstance().getTimeInMillis()));
}
--------
--------
Spring Data (JPA) Configuration
- All interaction of the application with the database will handle by the JPA library.
- JPA will have an Entity class and a corresponding Repository interface for all logical objects in the application.
Entity Class
xxxxxxxxxx
name = "tbl_users") (
public class Users implements Serializable {
private static final long serialVersionUID = 1L;
strategy = GenerationType.IDENTITY) (
name = "id", columnDefinition = "bigint") (
private Long id;
fetch = FetchType.EAGER) (
name = "user_account_id", columnDefinition = "bigint", nullable = false) (
private UserAccounts userAccount;
--------
--------
Repository Interface
xxxxxxxxxx
public interface UserRepository extends JpaRepository<Users, Long> {
/**
* To find user object using username
*
* @param username
* @return
*/
Users findByUserAccountUsername(String username);
---------
---------
- Other JPA configurations will be done in application.properties named file.
JPA Database Configuration in Application Properties
xxxxxxxxxx
spring.jpa.show-sql=false
spring.jpa.hibernate.dialect=org.hibernate.dialect.SQLServer2012Dialect
spring.jpa.hibernate.ddl-auto = update
spring.jpa.properties.hibernate.show_sql=false
spring.jpa.properties.hibernate.format_sql=false
spring.jpa.properties.hibernate.use_sql=true
spring.jpa.open-in-view=false
spring.jpa.properties.hibernate.hbm2ddl.auto=update
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
spring.jpa.hibernate.connection.provider_class=org.hibernate.hikaricp.internal.HikariCPConnectionProvider
Database Configuration
- The database name will be present in the application.properties file.
- Other information like connection URL and user credentials will be mentioned in two different other property files.
- application-dev.properties
- It will have the configurations which we used for the development.
- application-pro.properties
- It will have the configurations which we used for the production.
- application-dev.properties
spring.profiles.active=dev
- The above-mentioned property configuration will be present in the main "application.properties" file.
- It will decide which sub-property file should load to the system(dev or pro).
application.properties
#DB config
spring.datasource.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
application-dev.properties
#DB config
spring.datasource.url=jdbc:sqlserver://localhost:1433;databaseName=sample_webservice_db_dev
spring.datasource.username=dbuser
spring.datasource.password=ENC(tZTfehMYyz4EO0F0uY8fZItE7K35RtkA)
#spring.datasource.username=dbuser
#spring.datasource.password=dbuserpassword
application-pro.properties
#DB config
spring.datasource.url=jdbc:sqlserver://192.168.1.119:1433;databaseName=sample_webservice_db
spring.datasource.username=proUser
spring.datasource.password=ENC(proUserPswd)
Database Password Encryption
- The application database password will be encrypted using __Jasypt __ library with the help of an encryption key.
- This encryption key needs to add to the computer system variables of environmental variables under the "JASYPT_ENCRYPTOR_PASSWORD" named key.
- We have to mention the encrypted database password in the property file as follows. This is how the system will understand the password needs to be decrypted using a secret key which is added in the system variables.
spring.datasource.password=ENC(tZTfehMYyz4EO0F0uY8fZItE7K35RtkA)
- For the__Jasypt __ decryption we need to mention the default encryption configuration in the property file as follows:
jasypt.encryptor.algorithm=PBEWithMD5AndDES
jasypt.encryptor.iv-generator-classname=org.jasypt.iv.NoIvGenerator
- We also provide @EnableEncryptableProperties annotation in the application main class to let the application know about this database password encryption configuration.
SampleWebservice.java
xxxxxxxxxx
public class SampleWebservice extends SpringBootServletInitializer {
--------
--------
JWT Authentication Configuration
- We implemented JSON Web Token-based authentication with the help of spring security.
- Upon the success of a logged-in user, we will create two tokens (accessToken & refreshToken) and send them back to the client.
- accessToken will be created using a private key, expiry time (1 hr), user id, and role name.
- refreshToken will be created using a private key, expiry time (24 hr), user id, and role name.
- After successful login, each API request needs to have this accessToken in the header under the Authorization key.
- A "bearer" named key should be attached at the starting of the access token like follows.
- "bearer accessToken"
- The 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 the refresh token. If it is not expired we will give a new access token and refresh token.
- The client can continue using these new tokens.
- If the validity of the refresh token also expired, we ask them to re-login using their username and password.
Process of Creating Tokens
UnAuthorisedAccessServiceImpl.java
@Override
public ApiSuccessResponse userLoginService(String username, String password) {
Tokens tokens = null;
Users user = userService.findByUsername(username);
if (user != null) {
if (passwordEncryptingService.matches(password,
user.getUserAccount().getPassword())) {
if (user.getUserAccount().getStatus() == Constants.ACTIVE_STATUS) {
String roleName = user.getUserAccount().getUserRole().getRoleName();
// Creating new tokens
try {
tokens = createTokens(user.getUserAccount().getId().toString(), roleName);
} catch (Exception exception) {
logger.error("Token creation failed : ", exception);
throw new UnknownException();
}
// Validating tokens
if (validationService.validateTokens(tokens)) {
tokens.setUserId(user.getUserAccount().getId());
return new ApiSuccessResponse(tokens);
} else {
throw new UnknownException();
}
} else {
return new ApiSuccessResponse(new ApiResponseWithCode(Constants.USER_ACCOUNT_IS_INACTIVE_ERROR_CODE,
Constants.USER_ACCOUNT_IS_INACTIVE_ERROR_MESSAGE));
}
} else {
return new ApiSuccessResponse(new ApiResponseWithCode(Constants.USERNAME_OR_PASSWORD_IS_INCORRECT_ERROR_CODE,
Constants.USERNAME_OR_PASSWORD_IS_INCORRECT_ERROR_MESSAGE));
}
} else {
return new ApiSuccessResponse(new ApiResponseWithCode(Constants.USERNAME_OR_PASSWORD_IS_INCORRECT_ERROR_CODE,
Constants.USERNAME_OR_PASSWORD_IS_INCORRECT_ERROR_MESSAGE));
}
}
@Override
public ApiSuccessResponse createNewAccessTokenUsingRefreshToken(String refreshToken) {
Tokens tokens = null;
UserAccounts userAccount = null;
AppConfigSettings configSettings = appConfigSettingsService.findByConfigKeyAndStatus(Constants.JWT_SECRET_KEY,
Constants.ACTIVE_STATUS);
// Validate Refresh token
userAccount = jwtTokenHandler.validate(configSettings.getConfigValue(), refreshToken);
if (userAccount != null) {
// Creating new tokens if provided refresh token is valid
try {
tokens = createTokens(userAccount.getId().toString(), userAccount.getRole());
} catch (Exception exception) {
logger.error("Token creation failed : ", exception);
throw new UnknownException();
}
if (validationService.validateTokens(tokens)) {
tokens.setUserId(userAccount.getId());
return new ApiSuccessResponse(tokens);
} else {
throw new UnknownException();
}
} else {
return new ApiSuccessResponse(new ApiResponseWithCode(Constants.REFRESH_TOKEN_EXPIRED_ERROR_CODE,
Constants.REFRESH_TOKEN_EXPIRED_ERROR_MESSAGE));
}
}
- In the above code userLoginService named method will check the credentials of the user and provide tokens if it is valid.
- CreateNewAccessTokenUsingRefreshToken named method will create the new access token and refresh token upon the success refresh token validation.
Process of Filtering and Validating Tokens
WebConfig.java
xxxxxxxxxx
prePostEnabled = true) (
public class WebConfig extends WebSecurityConfigurerAdapter {
private JwtAuthenticationProvider authenticationProvider;
private JwtAuthenticationEntryPoint entryPoint;
public AuthenticationManager authenticationManager() {
return new ProviderManager(Collections.singletonList(authenticationProvider));
}
public JwtAuthenticationTokenFilter authenticationTokenFilter() {
JwtAuthenticationTokenFilter filter = new JwtAuthenticationTokenFilter();
filter.setAuthenticationManager(authenticationManager());
filter.setAuthenticationSuccessHandler(new JwtSuccessHandler());
return filter;
}
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.exceptionHandling().authenticationEntryPoint(entryPoint).and().sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.addFilterBefore(new WebSecurityCorsFilter(), ChannelProcessingFilter.class)
.addFilterBefore(authenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class)
.headers().cacheControl();
}
}
- This configuration will enable the spring security module using @EnableWebSecurity AND @EnableGlobalMethodSecurity(prePostEnabled = true) named annotations.
- Here we will inject the JWT filter into the HTTP request of the system.
JwtAuthenticationTokenFilter.java
public class JwtAuthenticationTokenFilter extends AbstractAuthenticationProcessingFilter {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private GeneralServices generalServices;
public JwtAuthenticationTokenFilter() {
super("/api/**");
}
@Override
public Authentication attemptAuthentication(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse) throws AuthenticationException, IOException, ServletException {
-------
--------
}
- Here, in the above class JwtAuthenticationTokenFilter() named method will filter all incoming web-service requests who have the "api" named keyword in the URL.
- All filtered web-service requests will reach the attemptAuthentication named method.
- We can do all our business logic in this method.
Application User Password Encryption
- All passwords of the users in this application will be encrypted for security using BCrypt.
PasswordEncryptingService.java
xxxxxxxxxx
public class PasswordEncryptingService {
public String encode(CharSequence rawPassword) {
return BCrypt.hashpw(rawPassword.toString(), BCrypt.gensalt(6));
}
public boolean matches(CharSequence rawPassword, String encodedPassword) {
return BCrypt.checkpw(rawPassword.toString(), encodedPassword);
}
- Here, the encode named method is used to encrypt the password.
- matches named method is used to cross-check the provided password and actual password of the user.
Log Configuration Using Slf4j
- We have one XML file to configure the Log named by logback-spring.xml.
- To log information from each class, we need to inject the respective class to Slf4j.
Example
UserServiceImpl.java
@Service("UserService")
@Scope("prototype")
public class UserServiceImpl implements UserService {
private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
- The above code snippet shows how we inject the class into the logger.
- Following are the basic methods to log the information.
- logger.error("Error");
- logger.info("Info");
- logger.warn("Warn");
Swagger For API Doc
- 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.
Pom.xml
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>${springfox.swagger.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${springfox.swagger.version}</version>
</dependency>
- 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.
SwaggerAPIDocConfig.java
xxxxxxxxxx
public class SwaggerAPIDocConfig {
public static final Contact DEFAULT_CONTACT = new Contact("Demo", "http://www.demo.ae/",
"info@demo.ae");
public static final ApiInfo DEFAUL_API_INFO = new ApiInfo("Sample Application",
"Sample Application description.",
"1.0.0",
"http://www.sampleapplication.ae/",
DEFAULT_CONTACT, "Open licence",
"http://www.sampleapplication.ae/#license",
new ArrayList<VendorExtension>());
private static final Set<String> DEFAULT_PRODICERS_AND_CONSUMERS =
new HashSet<>(Arrays.asList("application/json", "application/xml"));
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(DEFAUL_API_INFO)
.produces(DEFAULT_PRODICERS_AND_CONSUMERS)
.consumes(DEFAULT_PRODICERS_AND_CONSUMERS)
.select()
.apis(RequestHandlerSelectors.withClassAnnotation(RestController.class))
.paths(PathSelectors.any())
.build();
}
}
- As we can see in the above class, we need to add some basic information about our project.
- We need to tell Swagger from which class it 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.
Postman Script
- We can find 2 Postman JSON scripts 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.
Thank you!
Opinions expressed by DZone contributors are their own.
Comments