を作成し、FormAuthenticator
これを に設定しSecurityHandler
ますServletContextHandler
。このコードは、2 つのサーブレットを持つ単純なサーバーを作成します。最初のサーブレットは、認証されたユーザー名に hello メッセージで応答します。2 番目のサーブレットは、単純なログイン フォームを実装します。
コードを に貼り付けて実行できるはずですmain[]
(クラスパスに次の jar が必要です; 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();