[Spring Boot] Spring Boot Security REST + JPA + Hibernate + MySQL example | interface security verification and CRUD

This page will introduce examples of Spring Boot Security REST + JPA + Hibernate + MySQL CRUD. When we use Spring Boot t...
1. Use Eclipse
2. Use Maven command
3. Use executable jars

This page will introduce examples of Spring Boot Security REST + JPA + Hibernate + MySQL CRUD.

When we use Spring Boot to create an application, we only need to write a few lines of code to include functions such as network request, security authentication and database connection.

If Spring Boot obtains Spring Security in the classpath, it will automatically perform security related configuration.

Similarly, if Spring Boot obtains Spring Web and Spring Data in its classpath, Spring Boot will automatically perform the configuration related to Spring Web and database connection.

In terms of Spring Security, Spring Boot is configured with in memory authentication by default. It uses a user and random password, which will change every time the server is restarted. We can get the default password in the console.

In our example, we will save data related to user authentication in the database, so we must override the default security Configuration of Spring Boot. We will create a security profile with @ Configuration and @ EnableWebSecurity annotations.

To override HttpSecurity, our security configuration class needs to extend the WebSecurityConfigurerAdapter class and override the configure() method.

To enable method level security, annotate the security configuration class with @ EnableGlobalMethodSecurity.

In order to use the database to authenticate and authorize users, we need to implement the UserDetailsService interface.

We will handle create, read, update and delete operations in our REST network service example, which is called CRUD for short.

Let's discuss this complete example step by step.

Demo tool version
  1. Java 8
  2. Spring Boot 1.5.3.RELEASE
  3. Maven 3.3
  4. MySQL 5.5
  5. Eclipse Mars
Project structure

Spring Boot is the default authentication method

If spring security is in the classpath, our spring boot web application will automatically use basic authentication to ensure security by default.

A default user name "user" and random password will be displayed in the console at server startup and can be used for login authentication.

The password is displayed on the console as follows.

Using default security password: 7e9850aa-d985-471a-bae1-25d741d4da23

The above password is random and changes when the server restarts. By default, spring uses memory authentication, and a single user is named "user". Locate these configurations.

1. To enable spring security in the spring boot application, simply use the following spring boot configuration in the maven or gradle file.

spring-boot-starter-security

2. In order to change the default password, spring boot provides the security.user.password property, which needs to be configured in application.properties, as shown below.

security.user.password= concretepage

Now we can log in to the application using the user/concretepage credentials. Other security properties can also be changed by using the security. * prefix in application.properties through SecurityProperties, as shown below.

security.basic.enabled: enables basic authentication. The default value is true.

security.basic.path: configure the path that requires security authentication. We need to provide comma separated paths.

security.enable-csrf: enables and disables CSRF. The default value is false.

security.require-ssl: enable and disable SSL. The default value is false.

security.sessions: the default value is stateless. The values can be always, never, if_required, or stateless.

security.user.name: configure user name. The default user is user.

security.user.password: configure the password.

security.user.role: it configures the role. The default role is USER.

3. If we have fine tuned our log configuration, in order to print the default random password, we need to configure the following properties in application.properties with the level of INFO.

logging.level.org.springframework.boot.autoconfigure.security= INFO

4. By default, static paths are not subject to security verification, such as / css / * *, / js / * *, / images / * *, / webjars / * * and * * / favicon.ico.

5. Functions such as HSTS, XSS, CSRF and cache are provided by default in spring security.

The above properties can be turned on and off using security. *, but if we want to use the user name and password in the database, we need to use UserDetailsService.

To control the security related Configuration, we can create a security Configuration class that will extend WebSecurityConfigurerAdapter and override the configure() method. This class will be annotated as @ Configuration and @ EnableWebSecurity.

If we want to enable method level security, this class will be annotated as @ EnableGlobalMethodSecurity.

Maven file

pom.xml

<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.concretepage</groupId> <artifactId>spring-boot-demo</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>spring-demo</name> <description>Spring Boot Demo Project</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.3.RELEASE</version> </parent> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>

When the Spring Boot application finds any jars in the classpath, Spring Boot will automatically configure the required settings.

Spring boot starter Web: automatically configure web application settings.

Spring boot starter security: automatically configure security related settings.

Spring boot starter data JPA: automatically configure settings related to database connection.

application.properties

In Spring Boot, to configure database related properties, hibernate and logs, we need to use application.properties or application.yml. These files will be automatically read by Spring Boot.

application.properties

#spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/concretepage spring.datasource.username=root spring.datasource.password= spring.datasource.tomcat.max-wait=20000 spring.datasource.tomcat.max-active=50 spring.datasource.tomcat.max-idle=20 spring.datasource.tomcat.min-idle=15 spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQLDialect spring.jpa.properties.hibernate.id.new_generator_mappings = false spring.jpa.properties.hibernate.format_sql = true logging.level.org.hibernate.SQL=DEBUG logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE #Security Configuration--- #security.user.password= concretepage #prints default password--- #logging.level.org.springframework.boot.autoconfigure.security= INFO

Use spring.datasource. * to configure data source related properties. Use spring.jpa.properties. * to configure JPA related properties.

In our example, we are using JPA and hibernate.

MySQL tables and JAVA entities

Database Schema

CREATE DATABASE IF NOT EXISTS `concretepage` ; USE `concretepage`; -- Dumping structure for table concretepage.articles CREATE TABLE IF NOT EXISTS `articles` ( `article_id` int(5) NOT NULL AUTO_INCREMENT, `title` varchar(200) NOT NULL, `category` varchar(100) NOT NULL, PRIMARY KEY (`article_id`) ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1; -- Dumping data for table concretepage.articles: ~3 rows (approximately) INSERT INTO `articles` (`article_id`, `title`, `category`) VALUES (1, 'Java Concurrency', 'Java'), (2, 'Hibernate HQL ', 'Hibernate'), (3, 'Spring MVC with Hibernate', 'Spring'); -- Dumping structure for table concretepage.users CREATE TABLE IF NOT EXISTS `users` ( `username` varchar(50) NOT NULL, `password` varchar(100) NOT NULL, `full_name` varchar(100) NOT NULL, `role` varchar(50) NOT NULL, `country` varchar(100) NOT NULL, `enabled` tinyint(1) NOT NULL, PRIMARY KEY (`username`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- Dumping data for table concretepage.users: ~2 rows (approximately) INSERT INTO `users` (`username`, `password`, `full_name`, `role`, `country`, `enabled`) VALUES ('mukesh', '$2a$10$N0eqNiuikWCy9ETQ1rdau.XEELcyEO7kukkfoiNISk/9F7gw6eB0W', 'Mukesh Sharma', 'ROLE_ADMIN', 'India', 1), ('tarun', '$2a$10$QifQnP.XqXDW0Lc4hSqEg.GhTqZHoN2Y52/hoWr4I5ePxK7D2Pi8q', 'Tarun Singh', 'ROLE_USER', 'India', 1);

We have two tables users and articles.

In the users table, we save information related to users, and in the articles table, we save information related to articles.

We are using BCrypt cipher coding scheme.

Find a simple main class that can be used to generate BCrypt passwords.

Main.java

package com.concretepage; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; public class Main { public static void main(String[] args) { BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(); System.out.println(encoder.encode("m123")); } }

For the two tables given in the above database schema, find the java entity.

UserInfo.java

package com.concretepage.entity; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="users") public class UserInfo implements Serializable { private static final long serialVersionUID = 1L; @Id @Column(name="username") private String userName; @Column(name="password") private String password; @Column(name="role") private String role; @Column(name="full_name") private String fullName; @Column(name="country") private String country; @Column(name="enabled") private short enabled; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getRole() { return role; } public void setRole(String role) { this.role = role; } public String getFullName() { return fullName; } public void setFullName(String fullName) { this.fullName = fullName; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public short getEnabled() { return enabled; } public void setEnabled(short enabled) { this.enabled = enabled; } }

Article.java

package com.concretepage.entity; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="articles") public class Article implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.AUTO) @Column(name="article_id") private int articleId; @Column(name="title") private String title; @Column(name="category") private String category; public int getArticleId() { return articleId; } public void setArticleId(int articleId) { this.articleId = articleId; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } }
Create DAO for user authentication

In our example, we did not use the default memory authentication of Spring Boot. We will store user authentication related information in the MySQL database and access them using Hibernate. So we need to create a DAO method to return the user information of a given user name.

IUserInfoDAO.java

package com.concretepage.dao; import com.concretepage.entity.UserInfo; public interface IUserInfoDAO { UserInfo getActiveUser(String userName); }

UserInfoDAO.java

package com.concretepage.dao; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import com.concretepage.entity.UserInfo; @Repository @Transactional public class UserInfoDAO implements IUserInfoDAO { @PersistenceContext private EntityManager entityManager; public UserInfo getActiveUser(String userName) { UserInfo activeUserInfo = new UserInfo(); short enabled = 1; List<?> list = entityManager.createQuery("SELECT u FROM UserInfo u WHERE userName=? and enabled=?") .setParameter(1, userName).setParameter(2, enabled).getResultList(); if(!list.isEmpty()) { activeUserInfo = (UserInfo)list.get(0); } return activeUserInfo; } }

The Spring @Transactional annotation is used to make DAO methods transactional.

We use JPA's API to handle database transactions, so we will use dependency injection to instantiate EntityManager.

To achieve this, we created the EntityManager attribute with the @ PersistenceContext annotation.

Implement UserDetailsService

Spring provides UserDetailsService to authenticate and authorize users. It receives user related data from our DAO.

MyAppUserDetailsService.java

package com.concretepage.config; import java.util.Arrays; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import com.concretepage.dao.IUserInfoDAO; import com.concretepage.entity.UserInfo; @Service public class MyAppUserDetailsService implements UserDetailsService { @Autowired private IUserInfoDAO userInfoDAO; @Override public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException { UserInfo activeUserInfo = userInfoDAO.getActiveUser(userName); GrantedAuthority authority = new SimpleGrantedAuthority(activeUserInfo.getRole()); UserDetails userDetails = (UserDetails)new User(activeUserInfo.getUserName(), activeUserInfo.getPassword(), Arrays.asList(authority)); return userDetails; } }
Implement BasicAuthenticationEntryPoint

In our example, we use header based authentication.

When we don't use login page based authentication, Spring needs to send an error with the appropriate status code for any request to the application.

Spring provides basic authentication entrypoint, which needs to be implemented.

It has a method, conference (), which we will override and return a status code (401). The unauthorized status code contains the header of the authentication type required for authentication.

In our example, we use basic authentication.

AppAuthenticationEntryPoint.java

package com.concretepage.config; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint; import org.springframework.stereotype.Component; @Component public class AppAuthenticationEntryPoint extends BasicAuthenticationEntryPoint { @Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException { response.addHeader("WWW-Authenticate", "Basic realm=\"" + getRealmName() + "\""); response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException.getMessage()); } @Override public void afterPropertiesSet() throws Exception { setRealmName("MY APP REALM"); } }
Security configuration

We will now create a security profile.

SecurityConfig.java

package com.concretepage.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(securedEnabled=true) public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private MyAppUserDetailsService myAppUserDetailsService; @Autowired private AppAuthenticationEntryPoint appAuthenticationEntryPoint; @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable() .authorizeRequests() .antMatchers("/user/**").hasAnyRole("ADMIN","USER") .and().httpBasic().realmName("MY APP REALM") .authenticationEntryPoint(appAuthenticationEntryPoint); } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); auth.userDetailsService(myAppUserDetailsService).passwordEncoder(passwordEncoder); } }

This class has been annotated as @ EnableWebSecurity, which configures spring security from the WebSecurityConfigurer class.

If we want to override any method of WebSecurityConfigurer, we will extend WebSecurityConfigurerAdapter.

In our example, in order to configure HttpSecurity, we have overridden the configure() method.

Here, we have authorized a URL with / user / * * mode.

We will also configure the implementation class of BasicAuthenticationEntryPoint here.

Now, in the autowire method configureGlobal(), we have configured the implementation class of UserDetailsService with BCryptPasswordEncoder coding scheme.

To protect the service method, we need to use the @ EnableGlobalMethodSecurity annotation.

To enable method level security using the @ Secured annotation, configure the securedEnabled metadata with a value of true.

To enable the @ PreAuthorize and @ PostAuthorize annotations, configure the prePostEnabled metadata to true.

Create DAO for CRUD operation

Use the DAO class of JPA EntityManager for CRUD operations.

IArticleDAO.java

package com.concretepage.dao; import java.util.List; import com.concretepage.entity.Article; public interface IArticleDAO { List<Article> getAllArticles(); Article getArticleById(int articleId); void addArticle(Article article); void updateArticle(Article article); void deleteArticle(int articleId); boolean articleExists(String title, String category); }

ArticleDAO.java

package com.concretepage.dao; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import com.concretepage.entity.Article; @Transactional @Repository public class ArticleDAO implements IArticleDAO { @PersistenceContext private EntityManager entityManager; @Override public Article getArticleById(int articleId) { return entityManager.find(Article.class, articleId); } @SuppressWarnings("unchecked") @Override public List<Article> getAllArticles() { String hql = "FROM Article as atcl ORDER BY atcl.articleId"; return (List<Article>) entityManager.createQuery(hql).getResultList(); } @Override public void addArticle(Article article) { entityManager.persist(article); } @Override public void updateArticle(Article article) { Article artcl = getArticleById(article.getArticleId()); artcl.setTitle(article.getTitle()); artcl.setCategory(article.getCategory()); entityManager.flush(); } @Override public void deleteArticle(int articleId) { entityManager.remove(getArticleById(articleId)); } @Override public boolean articleExists(String title, String category) { String hql = "FROM Article as atcl WHERE atcl.title = ? and atcl.category = ?"; int count = entityManager.createQuery(hql).setParameter(1, title) .setParameter(2, category).getResultList().size(); return count > 0 ? true : false; } }
Create a Service with secure authentication CURD operation

Now, we will create a service method with security authentication for CRUD operations.

IArticleService.java

package com.concretepage.service; import java.util.List; import org.springframework.security.access.annotation.Secured; import com.concretepage.entity.Article; public interface IArticleService { @Secured ({"ROLE_ADMIN", "ROLE_USER"}) List<Article> getAllArticles(); @Secured ({"ROLE_ADMIN", "ROLE_USER"}) Article getArticleById(int articleId); @Secured ({"ROLE_ADMIN"}) boolean addArticle(Article article); @Secured ({"ROLE_ADMIN"}) void updateArticle(Article article); @Secured ({"ROLE_ADMIN"}) void deleteArticle(int articleId); }

Users with ADMIN role can access all methods. Users with USER role can only access getAllArticle() and getArticleById() service methods.

Now find the implementation class.

ArticleService.java

package com.concretepage.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.concretepage.dao.IArticleDAO; import com.concretepage.entity.Article; @Service public class ArticleService implements IArticleService { @Autowired private IArticleDAO articleDAO; @Override public Article getArticleById(int articleId) { Article obj = articleDAO.getArticleById(articleId); return obj; } @Override public List<Article> getAllArticles(){ return articleDAO.getAllArticles(); } @Override public synchronized boolean addArticle(Article article){ if (articleDAO.articleExists(article.getTitle(), article.getCategory())) { return false; } else { articleDAO.addArticle(article); return true; } } @Override public void updateArticle(Article article) { articleDAO.updateArticle(article); } @Override public void deleteArticle(int articleId) { articleDAO.deleteArticle(articleId); } }
Create Controller for CURD operation

Locate the controller class that has the CREATE, READ, UPDATE, and DELETE (CRUD) operation methods.

ArticleController.java

package com.concretepage.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.util.UriComponentsBuilder; import com.concretepage.entity.Article; import com.concretepage.service.IArticleService; @Controller @RequestMapping("user") public class ArticleController { @Autowired private IArticleService articleService; @GetMapping("article/") public ResponseEntity<Article> getArticleById(@PathVariable("id") Integer id) { Article article = articleService.getArticleById(id); return new ResponseEntity<Article>(article, HttpStatus.OK); } @GetMapping("articles") public ResponseEntity<List<Article>> getAllArticles() { List<Article> list = articleService.getAllArticles(); return new ResponseEntity<List<Article>>(list, HttpStatus.OK); } @PostMapping("article") public ResponseEntity<Void> addArticle(@RequestBody Article article, UriComponentsBuilder builder) { boolean flag = articleService.addArticle(article); if (flag == false) { return new ResponseEntity<Void>(HttpStatus.CONFLICT); } HttpHeaders headers = new HttpHeaders(); headers.setLocation(builder.path("/article/").buildAndExpand(article.getArticleId()).toUri()); return new ResponseEntity<Void>(headers, HttpStatus.CREATED); } @PutMapping("article") public ResponseEntity<Article> updateArticle(@RequestBody Article article) { articleService.updateArticle(article); return new ResponseEntity<Article>(article, HttpStatus.OK); } @DeleteMapping("article/") public ResponseEntity<Void> deleteArticle(@PathVariable("id") Integer id) { articleService.deleteArticle(id); return new ResponseEntity<Void>(HttpStatus.NO_CONTENT); } }

Starting with spring 4.3, we have a request mapping annotation, such as
@GetMapping: HTTP GET method
@PostMapping: HTTP POST method
@PutMapping: HTTP PUT method
@DeleteMapping: HTTP DELETE method

We created the following URL for CRUD operation.

1. Create :
Method: POST, website: / user/article

2. Read :
Method: GET, URL: / user/article/
Method: GET, URL: / user/articles

3. Update :
Method: PUT, website: / user/article

4. Delete :
Method: DELETE, website: / user/article/

Creating a main class using spring application

Create a class with a main() method that will call SpringApplication.run() to run the application.

First download all the JAR dependencies, then compile the project, and then start the embedded tomcat server.

MyApplication.java

package com.concretepage; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } }

We need to annotate this class with the @ SpringBootApplication annotation, which is equivalent to the @ Configuration, @ EnableAutoConfiguration and @ ComponentScan annotations.

Create a client using RestTemplate

To consume REST web services, we use RestTemplate. For authentication, we will pass Base64 encoded credentials in HttpHeaders as username:password token and perform basic authorization.

RestClientUtil.java

package com.concretepage.client; import java.net.URI; import org.apache.tomcat.util.codec.binary.Base64; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestTemplate; import com.concretepage.entity.Article; public class RestClientUtil { private HttpHeaders getHeaders() { String credential="mukesh:m123"; //String credential="tarun:t123"; String encodedCredential = new String(Base64.encodeBase64(credential.getBytes())); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.add("Authorization", "Basic " + encodedCredential); return headers; } public void getArticleByIdDemo() { HttpHeaders headers = getHeaders(); RestTemplate restTemplate = new RestTemplate(); String url = "http://localhost:8080/user/article/"; HttpEntity<String> requestEntity = new HttpEntity<String>(headers); ResponseEntity<Article> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, Article.class, 1); Article article = responseEntity.getBody(); System.out.println("Id:"+article.getArticleId()+", Title:"+article.getTitle() +", Category:"+article.getCategory()); } public void getAllArticlesDemo() { HttpHeaders headers = getHeaders(); RestTemplate restTemplate = new RestTemplate(); String url = "http://localhost:8080/user/articles"; HttpEntity<String> requestEntity = new HttpEntity<String>(headers); ResponseEntity<Article[]> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, Article[].class); Article[] articles = responseEntity.getBody(); for(Article article : articles) { System.out.println("Id:"+article.getArticleId()+", Title:"+article.getTitle() +", Category: "+article.getCategory()); } } public void addArticleDemo() { HttpHeaders headers = getHeaders(); RestTemplate restTemplate = new RestTemplate(); String url = "http://localhost:8080/user/article"; Article objArticle = new Article(); objArticle.setTitle("Spring REST Security using Hibernate"); objArticle.setCategory("Spring"); HttpEntity<Article> requestEntity = new HttpEntity<Article>(objArticle, headers); URI uri = restTemplate.postForLocation(url, requestEntity); System.out.println(uri.getPath()); } public void updateArticleDemo() { HttpHeaders headers = getHeaders(); RestTemplate restTemplate = new RestTemplate(); String url = "http://localhost:8080/user/article"; Article objArticle = new Article(); objArticle.setArticleId(1); objArticle.setTitle("Update:Java Concurrency"); objArticle.setCategory("Java"); HttpEntity<Article> requestEntity = new HttpEntity<Article>(objArticle, headers); restTemplate.put(url, requestEntity); } public void deleteArticleDemo() { HttpHeaders headers = getHeaders(); RestTemplate restTemplate = new RestTemplate(); String url = "http://localhost:8080/user/article/"; HttpEntity<Article> requestEntity = new HttpEntity<Article>(headers); restTemplate.exchange(url, HttpMethod.DELETE, requestEntity, Void.class, 4); } public static void main(String args[]) { RestClientUtil util = new RestClientUtil(); //util.getArticleByIdDemo(); util.getAllArticlesDemo(); //util.addArticleDemo(); util.updateArticleDemo(); //util.deleteArticleDemo(); } }

Here, we are performing create, read, update, and delete (CRUD) operations. We can test the application using mukesh/m123 with ADMIN role and tarun/t123 credentials with USER role.

Run application

To run the application, first create a table in MySQL, as shown in the example. Now we can run REST web services in the following ways.

1. Use Eclipse

Use the download link at the end of the page to download the source code of the project.

Import the project into eclipse.

Using the command prompt, go to the root folder of the project and run.

mvn clean eclipse:eclipse

Then refresh the project in eclipse. Click Run as - > java application to run the main class MyApplication.

The Tomcat server will be started.

2. Use Maven command

Download the source code of the project. Use the command prompt to go to the root folder of the project and run the command.

mvn spring-boot:run

The Tomcat server will be started.

3. Use executable jars

Using the command prompt, go to the root folder of the project and run the command.

mvn clean package

We will get the executable spring-boot-demo-0.0.1-SNAPSHOT.jar in the target folder. Run the JAR as follows.

java -jar target/spring-boot-demo-0.0.1-SNAPSHOT.jar

The Tomcat server will be started.

Now we are ready to test the application. To run the client, enter the RestClientUtil class in eclipse and click Run as - > java application.

We can also test the application using Postman.

As shown in the figure.

reference

[1]Spring Boot Security Features
[2]Spring Boot REST + JPA + Hibernate + MySQL Example
[3]Spring Boot Security REST + JPA + Hibernate + MySQL CRUD Example

Source download

Extraction code: mao4
spring-boot-security-rest-jpa-hibernate-mysql-crud-example.zip

13 October 2021, 14:12 | Views: 2705

Add new comment

For adding a comment, please log in
or create account

0 comments