Anand
Anand

Reputation: 21310

Implement basic Authentication for rest api using Jersey 2

I have exposed some rest api using Jersey 2(Tomcat server) and successfully implemented Basic authentication(only needed authentication stuff not authorization) using ContainerRequestFilter filter as below

public class AuthFilter implements ContainerRequestFilter{

    @Context
    HttpServletRequest request;

    @Override
    public void filter(ContainerRequestContext context)  {
     ............................
     //getting username/password authorization header and validating

When I told the same to my Lead, he said don't use filters as every time your rest api is hit, this filter will get invoked.Therefore, implement basic authentication security at container level.I am using Tomcat server. In web.xml, this is defined

<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>

Is the above he is referring to? Can anyone please guide me how to implement the way my lead is saying?

Upvotes: 1

Views: 5920

Answers (1)

Deepak Bala
Deepak Bala

Reputation: 11185

The documentation gives you examples on how to configure this via web.xml. You'll need to configure this using a login-config that belongs to a realm. The web container then takes care of securing resources based on URL patterns.

  • Note that the data is sent in plain text (in encoded form) via a HTTP header, so you'll need to think of ways to ensure that is not snooped on (like HTTPS).
  • Whether you check this header on a filter or on the container does not relieve you of the overhead required for making the check (which is probably negligible, but I've never profiled this area of the code to quote numbers).

Upvotes: 2

Related Questions