DZone
Integration Zone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
  • Refcardz
  • Trend Reports
  • Webinars
  • Zones
  • |
    • Agile
    • AI
    • Big Data
    • Cloud
    • Database
    • DevOps
    • Integration
    • IoT
    • Java
    • Microservices
    • Open Source
    • Performance
    • Security
    • Web Dev
DZone > Integration Zone > Technique to Shield Your API With @Namebinding

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.

Thamizh Arasu user avatar by
Thamizh Arasu
·
Jun. 14, 16 · Integration Zone · Tutorial
Like (3)
Save
Tweet
4.02K Views

Join the DZone community and get the full member experience.

Join For Free

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

@NameBinding
@Retention(RetentionPolicy.RUNTIME)
public @interface ApiKeyProtected {}

Filter with annotation

@ApiKeyProtected
public class ApiKeyCheckFilter implements ContainerRequestFilter {
    private static final Logger logger = LogManager.getLogger(ApiKeyCheckFilter.class);

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {
        logger.info("Requested Path: {}", requestContext.getUriInfo().getPath());

        final String apiKeyValue = requestContext.getHeaderString("X-API-KEY");
        if (apiKeyValue == null || apiKeyValue.isEmpty()) {
            requestContext.abortWith(Response.status(
                    Response.Status.UNAUTHORIZED)
                    .entity("X-API-KEY is missing in the header")
                    .build());
        }
    }
}

Resource method with annotation

@GET
@Path("{id}")
@ApiKeyProtected
Response get(@PathParam("id") String id);

@POST
@Consumes(MediaType.APPLICATION_JSON)
Response create(User user);

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!

API

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

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • The Evolution of Configuration Management: IaC vs. GitOps
  • How to Hash, Salt, and Verify Passwords in NodeJS, Python, Golang, and Java
  • JUnit 5 Tutorial: Nice and Easy [Video]
  • Making Your SSR Sites 42x Faster With Redis Cache

Comments

Integration Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • MVB Program
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends:

DZone.com is powered by 

AnswerHub logo