2

私は、pax web を使用するコンテナーとして Karaf 3.0.2 を使用しています (これもまた jetty を使用していると思います)。特定のエイリアスで OSGi サービスとして登録するいくつかのサーブレットがあります。

デフォルトでは、etc/jetty.xml は JAASLoginService を使用できるように構成されていますが、これは既に使用したいサービスでもあります。

問題は、基本認証とフォーム認証の両方を使用したいということです。

  • /ui/* に一致するものはすべてフォーム認証を使用する必要があります
  • /rest/* に一致するものはすべて基本認証を使用する必要があります

いろいろ試しましたが、どこから始めればよいかさえわかりませんでした。サーブレットごとに設定することは可能だと思いますが、グローバルに行いたいです。

何か案は?

4

1 に答える 1

2

ここで少し区別する必要があります。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());
        }
    }
...
}
于 2014-10-27T21:18:04.120 に答える