简体   繁体   中英

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?

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM