Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Technique to Shield Your API With @Namebinding

DZone's Guide to

Technique to Shield Your API With @Namebinding

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.

· Integration Zone
Free Resource

Modernize your application architectures with microservices and APIs with best practices from this free virtual summit series. Brought to you in partnership with CA Technologies.

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, registering a user doesn’t require any kind of security check, whereas, when getting the user information, we need some kind of security restrictions. How can this be achieved using the Jersey framework?

Solution:

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

  • Introduce an interface with the @NameBinding annotation.
  • Introduce a Container Request filter with our custom annotation.
  • Use our annotation in our API (to require the 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 for any header.

Cool, right?

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

The Integration Zone is proudly sponsored by CA Technologies. Learn from expert microservices and API presentations at the Modernizing Application Architectures Virtual Summit Series.

Topics:
api security ,api key

Published at DZone with permission of Thamizh Arasu, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}