javabasic-authenticationembedded-jettyjetty-8

Embedded Jetty Defining Realm without Jetty.xml


I use embedded Jetty at my application and I don't want to use an external xml file (jetty.xml). I want to implement a security layer. This is what I want to do:

<Configure class="org.eclipse.jetty.webapp.WebAppContext">
  <Set name="contextPath">/test</Set>
  <Set name="war"><SystemProperty name="jetty.home" default="."/>/webapps/test</Set>

  <Get name="securityHandler">
    <Set name="loginService">
      <New class="org.eclipse.jetty.security.HashLoginService">
            <Set name="name">Test Realm</Set>
            <Set name="config"><SystemProperty name="jetty.home" default="."/>/etc/realm.properties</Set>
      </New>
    </Set>
  </Get>

</Configure>

How can I add it into my embedded jetty without a jetty.xml (I'll just use realm.properties as an external file).

Embedded Jetty

Jetty Realms


Solution

  • Here is how it is done:

    Server server = new Server();
    
    Connector connector = new SelectChannelConnector();
    connector.setPort(8080);
    server.setConnectors(new Connector[]{connector});
    
    WebAppContext webappcontext = new WebAppContext();
    webappcontext.setContextPath("/mywebapp");
    webappcontext.setWar("./path/to/my/war/orExplodedwar");
    
    HandlerCollection handlers= new HandlerCollection();
    handlers.setHandlers(new Handler[]{webappcontext, new DefaultHandler()});
    
    server.setHandler(handlers);
    HashUserRealm myrealm = new HashUserRealm("MyRealm",System.getProperty("jetty.home")+"/etc/realm.properties");
    server.setUserRealms(new UserRealm[]{myrealm});
    
    server.start();
    server.join();
    

    Jetty Documentation