Technique to shield your API with @NameBinding

0
918
Shield your API
How to shield your API with @NameBinding
Learn on Udemy Today!

Problem:

When we develop a REST API for our business, we may need to protect some of our APIs using API key or some kind of security mechanism. This can be achieved using Container Request Filter option available in Jersey framework. But in some cases we may need to ignore this validation or bypass this filter and allow our API call. For example, we can consider user CRUD REST API. /users is our main entry point to reach our REST API. Here for registering¬†an user doesn’t require any kind of security check. Whereas for getting the user information, we need some kind of security restrictions. How this can be achieved using Jersey framework?

Solution

To achieve the above use-case we can use @NameBinding annotation which is available in Jersey. Follow the 3 simple steps to get that working.

  • Introduce an interface with @NameBinding annotation
  • Introduce a Container Request filter with our custom annotation
  • Use our annotation to our API (Require security check)

@NameBinding annotation

 

Filter with annotation

 

Resource method with annotation

We are done with our implementation. When you try to access the GET API, it will ask you to pass the X-API-KEY header value along with your header parameter. whereas when you access the POST API, it won’t ask you any header.

Cool right!

I hope you have enjoyed this article. Please share the article with your friends and ask question if you have any!

SHARE
Previous articlePowerful tactic to use exception mapper in Dropwizard
Next articleRESTful Java: Developer handbook
Thamizharasu is a Java developer living in India. He is writing about Java programming, RESTful web services and frameworks. He also loves working with Web API, Elastic search and Firebase. Currently he is a Madras JUG lead and you can follow him on Twitter @zarub2k