View Javadoc

1   // ========================================================================
2   // Copyright (c) 2006-2009 Mort Bay Consulting Pty. Ltd.
3   // ------------------------------------------------------------------------
4   // All rights reserved. This program and the accompanying materials
5   // are made available under the terms of the Eclipse Public License v1.0
6   // and Apache License v2.0 which accompanies this distribution.
7   // The Eclipse Public License is available at 
8   // http://www.eclipse.org/legal/epl-v10.html
9   // The Apache License v2.0 is available at
10  // http://www.opensource.org/licenses/apache2.0.php
11  // You may elect to redistribute this code under either of these licenses. 
12  // ========================================================================
13  
14  package org.eclipse.jetty.embedded;
15  
16  import java.util.HashSet;
17  import java.util.Set;
18  
19  import org.eclipse.jetty.http.security.Constraint;
20  import org.eclipse.jetty.security.ConstraintMapping;
21  import org.eclipse.jetty.security.ConstraintSecurityHandler;
22  import org.eclipse.jetty.security.HashLoginService;
23  import org.eclipse.jetty.security.LoginService;
24  import org.eclipse.jetty.security.authentication.BasicAuthenticator;
25  import org.eclipse.jetty.server.Server;
26  
27  public class SecuredHelloHandler
28  {
29      public static void main(String[] args) throws Exception
30      {
31          Server server = new Server(0);
32          
33          LoginService loginService = new HashLoginService("MyRealm","src/test/resources/realm.properties");
34          server.addBean(loginService); 
35  
36          ConstraintSecurityHandler security = new ConstraintSecurityHandler();
37          server.setHandler(security);
38  
39          Constraint constraint = new Constraint();
40          constraint.setName("auth");
41          constraint.setAuthenticate( true );
42          constraint.setRoles(new String[]{"user", "admin"});
43  
44          ConstraintMapping mapping = new ConstraintMapping();
45          mapping.setPathSpec( "/*" );
46          mapping.setConstraint( constraint );
47  
48          Set<String> knownRoles = new HashSet<String>();
49          knownRoles.add("user");
50          knownRoles.add("admin");
51          
52          security.setConstraintMappings(new ConstraintMapping[] {mapping}, knownRoles);
53          security.setAuthenticator(new BasicAuthenticator());
54          security.setLoginService(loginService);
55          security.setStrict(false);
56          
57          HelloHandler hh = new HelloHandler();
58          
59          security.setHandler(hh);
60          
61          server.start();
62          server.join();
63      }
64  }