Servlet Basic Auth in an OSGi environment

You will first need to get a reference to the OSGI HTTP Service. You can do this through a declarative service. This post will concentrate on steps after getting a reference to the HTTP Service. Note: The complete class for this post is located here
When registering a servlet through the OSGI HTTP Service, it provides you with an option to provide an implementation of HTTPContext.
 
 
 
 
 
 

httpService.registerServlet(alias, new MyServlet(), initParams, null);

When we implement the HTTPContext interface we can implement three methods. Out of these three (3) handleSecurity will be called before serving a request to ermmm… check for security.

public class BasicAuthSecuredContext implements HttpContext{
    @Override
    public boolean handleSecurity(HttpServletRequest request, HttpServletResponse response) throws IOException {
        return false;
    }

    @Override
    public URL getResource(String s) {
        return null;  
    }

    @Override
    public String getMimeType(String s) {
        return null;
    }
}

So, when implementing this, I’m borrowing a lot of content from the OSGI HTTPContext documentation and the HTTP Authentication spec. They are a must read, if you are interested in learning a lot, diving into details, etc. or you can just read the rest of this post.

First, it is a big no-no to do basic auth unless https is used. If it’s not there we let the user know it’s forbidden territory. Let’s go ahead and do that.

if (!request.getScheme().equals("https")) {
    response.sendError(HttpServletResponse.SC_FORBIDDEN);
    return false;
}

Next, let’s check for the Authorization header. If that’s not there we let them know, they need that shit to be there. Or we just say they’re unauthorized. Let’s do that now.

if (request.getHeader("Authorization") == null) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
}

Ok, two tests passed. Now, we do some real work. Let’s extract the header decode it, and do “not so proper” authentication.

    protected boolean authenticated(HttpServletRequest request) {
        String authzHeader = request.getHeader("Authorization");
        String usernameAndPassword = new String(Base64.decodeBase64(authzHeader.substring(6).getBytes()));

        int userNameIndex = usernameAndPassword.indexOf(":");
        String username = usernameAndPassword.substring(0, userNameIndex);
        String password = usernameAndPassword.substring(userNameIndex + 1);
        // Now, do the authentication against in the way you want, ex: ldap, db stored uname/pw
        // Here I will do lame hard coded credential check. HIGHLY NOT RECOMMENDED! 
        return ((username.equals("username") && password.equals("password"));
    }

Let’s integrate this method, into the handleSecurity method. Notice how a meaningful error message is set to the response (line 14) when the security fails. This prevents the user from guessing, and they knows what exactly went wrong. Ermm, at least, if they know HTTP error codes they would know exactly what went wrong.

    @Override
    public boolean handleSecurity(HttpServletRequest request, HttpServletResponse response) throws IOException {
        if (!request.getScheme().equals("https")) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            return false;
        }
        if (request.getHeader("Authorization") == null) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        if (authenticated(request)) {
            return true;
        } else {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
    }

That’s it. Now, pass this object when registering the servlet,

httpService.registerServlet(alias, new MyServlet(), initParams, new BasicAuthSecuredContext());

…and behold the power of basic auth in OSGI servlets!

Reference: Implementing Basic Auth for a servlet in an OSGI environment from our JCG partner Mackie Mathew at the dev_religion blog.

Related Whitepaper:

Best Practices for Secure Software Development

Best practices for all organizations that would like to produce more secure applications!

As part of the software development process, security professionals must make choices about where to invest their budget and staff resources to ensure that homegrown applications are as secure as possible. ESG research found organizations that are considered security leaders tend to make different choices than other firms.

Get it Now!  

Leave a Reply


× four = 36



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

15,153 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books