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.Collections;
17  import java.util.HashSet;
18  import java.util.Set;
19  
20  import org.eclipse.jetty.http.security.Constraint;
21  import org.eclipse.jetty.security.ConstraintMapping;
22  import org.eclipse.jetty.security.ConstraintSecurityHandler;
23  import org.eclipse.jetty.security.HashLoginService;
24  import org.eclipse.jetty.security.LoginService;
25  import org.eclipse.jetty.security.authentication.BasicAuthenticator;
26  import org.eclipse.jetty.server.Server;
27  
28  public class SecuredHelloHandler
29  {
30      public static void main(String[] args) throws Exception
31      {
32          Server server = new Server(0);
33          
34          LoginService loginService = new HashLoginService("MyRealm","src/test/resources/realm.properties");
35          server.addBean(loginService); 
36  
37          ConstraintSecurityHandler security = new ConstraintSecurityHandler();
38          server.setHandler(security);
39  
40          Constraint constraint = new Constraint();
41          constraint.setName("auth");
42          constraint.setAuthenticate( true );
43          constraint.setRoles(new String[]{"user", "admin"});
44  
45          ConstraintMapping mapping = new ConstraintMapping();
46          mapping.setPathSpec( "/*" );
47          mapping.setConstraint( constraint );
48  
49          Set<String> knownRoles = new HashSet<String>();
50          knownRoles.add("user");
51          knownRoles.add("admin");
52          
53          security.setConstraintMappings(Collections.singletonList(mapping), knownRoles);
54          security.setAuthenticator(new BasicAuthenticator());
55          security.setLoginService(loginService);
56          security.setStrict(false);
57          
58          HelloHandler hh = new HelloHandler();
59          
60          security.setHandler(hh);
61          
62          server.start();
63          server.join();
64      }
65  }