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
│   └───main
│       ├───java
│       │   └───com
│       │       └───p1coder
│       │           │
│       │           │
│       │           │
│       │           ├───controller
│       │           │
│       │           │
│       │           ├───domain
│       │           │
│       │           │
│       │           └───service
│       │         
│       │         
│       └───webapp
│           └───WEB-INF
│               └───views
│                   └───product
│                           display.jsp
Fill each file with the sample code from each code section.
After maven update the reference packages, we can execute the sample by right click on project and choosing "Run as" -> "Spring Boot App".
       In, 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 "" 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, BasicAuthenticationInterceptor is used to authenticate while retrieving by HTTP GET execute on RestTemplate instance.
       In, ObjectMapper instance is used to deserialize the generic return value from data service call instantiated by @Autowired Dependency Injection.


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

  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


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....