ここで少し区別する必要があります。WebApplicationBundle (WAB) を使用してサーブレットをデプロイする場合、Web アプリケーションのすべての通常の要素があります。Basic または Form ベースの認証を含みます。
OSGi の方法でサーブレットを登録しているため、これは HttpContext を使用してのみ行うことができます。以下の例は、Pax Web サンプルから取得したもので、基本認証を使用しています。
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;
}
...
}
フォームベースの場合、追加の HttpContext が必要になります。適切な HttpContext が登録されていることを確認する必要があるすべての一致するパスについて、次のコードはPax Web サンプルにもあります。
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());
}
}
...
}