FormAuthenticator
を作成し、ServletContextHandler
のためにあなたのSecurityHandler
でこれを設定します。このコードは、2つのサーブレットを持つ簡単なサーバーを作成します。最初のサーブレットは、認証されたユーザー名へのhelloメッセージで応答します。 2番目のサーブレットは簡単なログインフォームを実装しています。
main[]
にコードを貼り付けて実行する必要があります(クラスパスには、jetty-server
、jetty-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();
これを有効にすることはできませんでした... – oshai
ありがとうございました!これは私には役に立ちました。私はそれを機能させることができました。 – mwhidden
これは役に立ちますが、私はあなたがそれをどうやって知っているのだろうと思っています。桟橋のドキュメンテーションは...無礼で、疎ではありません。例えば、 'ConstraintMapping'は完全に文書化されておらず、Googleはそれに関する情報をまったく提供していません。それを学ぶために内部のJettyのコードを読まなければなりませんか? – Timmmm