javajerseywebsphere-6.1basic-authenticationtomcat

Is there a server agnostic way to implement BASIC Authentication?


I am attempting to add BASIC authentication to my RESTful web-service. Currently I have BASIC authentication for an Apache Tomcat 6.0 server, but I need to deploy my web-service on a WebSphere application server ver. 6.1 as well and I am having problems getting BASIC authentication running on WebSphere.

Is there a way in Java to check the authentication headers of an HTTP request and if the username/password provided (in Base64 encoding) doesn't match a known account force the user to enter in a new username/password?

I have tried implementing Spring Security, but since my project was made entirely without Spring it has been a huge pain trying to get it to work, and I am attempting to find a simple solution to my rather simple problem.

Technologies that I am currently using include: Java, Jersey/JAX-RS, Eclipse with Maven plugin.


Solution

  • You should be able to setup a servlet filter which gets executed before your REST handlers, inspects the "Authorization" request header, base 64 decodes it, extracts the username and password, and verifies. Something like this:

    public void doFilter(ServletRequest req,
                         ServletResponse res,
                         FilterChain chain) {
      if (request instanceof HttpServletRequest) {
        HttpServletRequest request = (HttpServletRequest) req;
        String authHeader = Base64.decode(request.getHeader("Authorization"));
        String creds[] = authHeader.split(":");
        String username = creds[0], password = creds[1];
        // Verify the credentials here...
        if (authorized) {
          chain.doFilter(req, res, chain);
        } else {
          // Respond 401 Authorization Required.
        }
      }
      doFilter(req, res, chain);
    }
    

    All servlet containers have a standard way to configure filter chains.