Search code examples
jax-rsjax-wsbasic-authentication

Browser not prompting for credentials using basic authentication


My goal is to provide authentication to a single resource on the server, for this I am using custom filter. I am not using @NameBinding because of constraint of using JAVA 1.6.Using Response.header(HttpHeaders.WWW_AUTHENTICATE,"Basic") is not prompting for credentials.

Using ContainerRequestFilter is not helping my cause as it will put filter on every resource of server.

Filter

@Provider
public class AuthenticationFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp,
            FilterChain chain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) req;

        System.out.println("Entered authentication filter");

        throw new WebApplicationException(Response.status(Response.Status.UNAUTHORIZED)
                .header(HttpHeaders.AUTHORIZATION,"Basic")
                .entity("Credentials are required to access this resource.")
                .build());

//      chain.doFilter(req, resp);

    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {}

    @Override
    public void destroy() {}
}

web.xml mapping

<filter>
    <filter-name>AuthenticationFilter</filter-name>
    <filter-class>Utils.LDAPAuthentication.AuthenticationFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>AuthenticationFilter</filter-name>
    <url-pattern>/download</url-pattern>
  </filter-mapping>

The response I am getting on hitting the webservice is enter image description here


Solution

  • So as suggested by Paul , I used HttpServletResponse.

    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) resp;
    if(request.getHeader("Authorization")==null){
        response.setHeader(HttpHeaders.WWW_AUTHENTICATE,"Basic");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    }
    else{
        String credentials = request.getHeader("Authorization");
    }