Monday, December 24, 2018

How to consume REST API secured by Spring Security?

In this article, I am going to demostrate how we could access the REST api secured by Spring Security to display in front-end. We are going to use Spring Tool Suite (STS).
Create a new Java Project in STS and add the files into it similar to the following structure.
│         pom.xml
├───src
│   └───main
│       ├───java
│       │   └───com
│       │       └───p1coder
│       │           │   MvcConfiguration.java
│       │           │   SecurityConfig.java
│       │           │   SpringBootWebApplication.java
│       │           ├───controller
│       │           │       ProductController.java
│       │           │       RequestHandler.java
│       │           ├───domain
│       │           │       Product.java
│       │           │       UserPreference.java
│       │           └───service
│       │                   ProductService.java
│       │                   RestApiService.java
│       └───webapp
│           └───WEB-INF
│               └───views
│                   └───product
│                           display.jsp
Fill each file with the sample code from each code section.

MvcConfiguration.java
SecurityConfig.java
SpringBootWebApplication.java
ProductController.java
RequestHandler.java
ProductController.java
RequestHandler.java
Product.java
UserPreference.java
ProductService.java
RestApiService.java
display.jsp
pom.xml
After maven update the reference packages, we can execute the sample by right click on project and choosing "Run as" -> "Spring Boot App".
       In RequestHandler.java, we have REST api routes accessible by either PathVariable or RequestParam, which read the repository layer data.
       If we directly access "http://localhost:8080/getAllProducts" api, we will get authentication dialog box as we secure the route ("/getAllProducts**") in "SecurityConfig.java" file. This route is granted only to "admin" role by extending the WebSecurityConfigurerAdapter class.
       We will see the sample listing when we access "http://localhost:8080/products" page. We implement the data retrieval logic and pass api credential to REST api.
       In RestApiService.java, BasicAuthenticationInterceptor is used to authenticate while retrieving by HTTP GET execute on RestTemplate instance.
       In ProductController.java, ObjectMapper instance is used to deserialize the generic return value from data service call instantiated by @Autowired Dependency Injection.
Output

30 comments:

  1. Replies
    1. I am glad to know this blog helps the reader, Kiruthika. Thanks.

      Delete
  2. Thanks for the interesting blog that you have implemented here. Very helpful and innovative. Waiting for your next upcoming article.
    Digital Marketing Course In Kolkata

    ReplyDelete

Image compression using C#

Sometimes, we need to compress the image files while maintaining the image quality. This can be achieved by the following C# implementation....