6

以下のようにフォームベースの認証をプログラムで追加する方法はありますか? 私は自分のものを使用していLdapLoginModuleます。最初は基本認証を使用していて問題なく動作していましたが、ログインページをより細かく制御したい (ロゴの表示など)

良いサンプルはありますか?

私は組み込みの桟橋 v8.1.7 を使用しています。埋め込まれた桟橋に web.xml は使用しません。jetty サーバーは、プログラムによって開始されます。

<login-config>
    <auth-method>FORM</auth-method>
    <realm-name>Test JAAS Realm</realm-name>
    <form-login-config>
        <form-login-page>/login.html</form-login-page>
        <form-error-page>/error.jsp</form-error-page>
    </form-login-config>
</login-config>
4

1 に答える 1

11

を作成し、FormAuthenticatorこれを に設定しSecurityHandlerますServletContextHandler。このコードは、2 つのサーブレットを持つ単純なサーバーを作成します。最初のサーブレットは、認証されたユーザー名に hello メッセージで応答します。2 番目のサーブレットは、単純なログイン フォームを実装します。

コードを に貼り付けて実行できるはずですmain[](クラスパスに次の jar が必要です; jetty-serverjetty-servletおよびjetty-security)。テストするには、ブラウザーで をポイントします。http://localhost:8080の応答が表示される前に、資格情報 (ユーザー名/パスワード) の入力を求めるプロンプトが表示されますhello username

Server server = new Server(8080);
ServletContextHandler context = new ServletContextHandler(server, "/", ServletContextHandler.SESSIONS | ServletContextHandler.SECURITY);

context.addServlet(new ServletHolder(new DefaultServlet() {
  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.getWriter().append("hello " + request.getUserPrincipal().getName());
  }
}), "/*");

context.addServlet(new ServletHolder(new DefaultServlet() {
  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.getWriter().append("<html><form method='POST' action='/j_security_check'>"
      + "<input type='text' name='j_username'/>"
      + "<input type='password' name='j_password'/>"
      + "<input type='submit' value='Login'/></form></html>");
    }
}), "/login");

Constraint constraint = new Constraint();
constraint.setName(Constraint.__FORM_AUTH);
constraint.setRoles(new String[]{"user","admin","moderator"});
constraint.setAuthenticate(true);

ConstraintMapping constraintMapping = new ConstraintMapping();
constraintMapping.setConstraint(constraint);
constraintMapping.setPathSpec("/*");

ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler();
securityHandler.addConstraintMapping(constraintMapping);
HashLoginService loginService = new HashLoginService();
loginService.putUser("username", new Password("password"), new String[] {"user"});
securityHandler.setLoginService(loginService);

FormAuthenticator authenticator = new FormAuthenticator("/login", "/login", false);
securityHandler.setAuthenticator(authenticator);

context.setSecurityHandler(securityHandler);

server.start();
server.join();
于 2013-01-28T07:27:38.563 に答える