0

I have a rest controller API in a spring boot project. I need to add a common function, for example, validating the token of each incoming request before all the routes in that controller rather than calling the same function separately for each routes. Is there a way to achieve that with @Restcontroller based routing instead of going with web flux handler and router way?

Edit: Is there a way to use interceptors only for certain routes rather than all incoming requests?

Current version example:

@RestController
@RequestMapping("/api/")
class TestController() {

@GetMapping("/test1")
fun test1(): String {
  common()
  return "Test1"
 }
 @GetMapping("/test2")
 fun test2(): String {
   common()
   return "Test2"
 }

 fun common() {
   //some validation logic
 }
}
Dev
  • 1
  • 2
  • Does this answer your question? [Spring Boot Adding Http Request Interceptors](https://stackoverflow.com/questions/31082981/spring-boot-adding-http-request-interceptors) – samabcde Nov 19 '20 at 05:46
  • You can use a `HandlerINterceptor` for that. But as this feels like you are attempting to build your own security solution, I would strongly suggest to use Spring Security instead of building your own framework. – M. Deinum Nov 19 '20 at 06:31
  • Thanks for the answers. I need to use the token mechanism for only certain routes, for example, only the routes under " /externalapi/* ". other routes may or may not use the same security measures. Instead of using interceptors for all http requests, is there a way to filter out only certain routes? – Dev Nov 19 '20 at 14:41

1 Answers1

0

you normally develop filters to deal with security on Springboot. Filters intercept all calls made to your application where you can check the existence of a token avoiding unauthorized access. Please refer to this page for more grained details: https://medium.com/@xoor/jwt-authentication-service-44658409e12c.

Nikola Despotoski
  • 49,966
  • 15
  • 119
  • 148
rod.dinis
  • 1,233
  • 2
  • 11
  • 20
  • Thanks for the response. But i was looking for adding interceptor for one specific controller routes rather than all incoming http requests. – Dev Nov 27 '20 at 02:07