You have do differentiate here a bit.
If you use a WebApplicationBundle (WAB) to deploy your Servlets you have all regular elements of a Web Application. Including Basic or Form based authentication.
Since you are using the OSGi way of registering Servlets you only can do this by the means of the HttpContext. The below example is taken from the Pax Web Samples, it uses Basic Authentication.
public class AuthHttpContext implements HttpContext {
public boolean handleSecurity(HttpServletRequest req,
HttpServletResponse res) throws IOException {
if (req.getHeader("Authorization") == null) {
res.sendError(HttpServletResponse.SC_UNAUTHORIZED);
return false;
}
if (authenticated(req)) {
return true;
} else {
res.sendError(HttpServletResponse.SC_UNAUTHORIZED);
return false;
}
}
protected boolean authenticated(HttpServletRequest request) {
request.setAttribute(AUTHENTICATION_TYPE, HttpServletRequest.BASIC_AUTH);
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);
// Here I will do lame hard coded credential check. HIGHLY NOT RECOMMENDED!
boolean success = ((username.equals("admin") && password
.equals("admin")));
if (success)
request.setAttribute(REMOTE_USER, "admin");
return success;
}
...
}
For Form-based you'll need an extra HttpContext. For every matching path you need to make sure to have the right HttpContext registered, the following code can also be found at the Pax Web Samples.
public final class Activator implements BundleActivator {
...
public void start(BundleContext bc) throws Exception {
httpServiceRef = bc.getServiceReference(HttpService.class);
if (httpServiceRef != null) {
httpService = (HttpService) bc.getService(httpServiceRef);
...
httpService.registerServlet("/status-with-auth",
new StatusServlet(), null, new AuthHttpContext());
}
}
...
}