2011-11-08 8 views
7

Ho un'implementazione incorporata di Jetty 7 in esecuzione come servizio e voglio aggiungere l'autenticazione di base senza file web.xml per un servlet.Autenticazione di base con server Jetty 7 incorporato e nessun file web.xml

ho creato le mie credenziali utilizzando la procedura descritta here

ho pensato che avrei potuto creare il server, creare un gestore di sicurezza con l'autenticazione di base e allegare un HashLoginService al responsabile della sicurezza. Ma mi mancano chiaramente diverse cose, perché non ricevo mai richieste di credenziali.

Di seguito è riportato il codice. Qualsiasi aiuto sarebbe molto apprezzato.

server = new Server(port); 
    server.addConnector(getSslChannelConnector(securePort)); 
    server.setGracefulShutdown(1000); 
    server.setStopAtShutdown(true); 

    // create the context handler for the server 
    ServletContextHandler sch = new ServletContextHandler(server, WEBAPP_CONTEXT); 

    // attach the security handler to it that has basic authentication 
    sch.setSecurityHandler(getSecurityHandler()); 

    // define the processing servlet. 
    sch.addServlet(new ServletHolder(new ProcessingServlet()), "/process"); 

    . 
    . 
private SecurityHandler getSecurityHandler() { 

    // add authentication 
    Constraint constraint = new Constraint(Constraint.__BASIC_AUTH,"user"); 
    constraint.setAuthenticate(true); 
    constraint.setRoles(new String[]{"user","admin"}); 

    // map the security constraint to the root path. 
    ConstraintMapping cm = new ConstraintMapping(); 
    cm.setConstraint(constraint); 
    cm.setPathSpec("/*"); 

    // create the security handler, set the authentication to Basic 
    // and assign the realm. 
    ConstraintSecurityHandler csh = new ConstraintSecurityHandler(); 
    csh.setAuthenticator(new BasicAuthenticator()); 
    csh.setRealmName(REALM); 
    csh.addConstraintMapping(cm); 

    // set the login service 
    csh.setLoginService(getHashLoginService()); 

    return csh; 

} 
private HashLoginService getHashLoginService() { 

    // create the login service, assign the realm and read the user credentials 
    // from the file /tmp/realm.properties. 
    HashLoginService hls = new HashLoginService(); 
    hls.setName(REALM); 
    hls.setConfig("/tmp/realm.properties"); 
    hls.setRefreshInterval(0); 
    return hls; 
} 

risposta

11

Ho ottenuto questo lavoro e inviato un campione webapp here

+0

Grazie, opere di esempio. – ozhan

0

Il codice sembra ampiamente ok. mia interfaccia è leggermente diversa per aggiungere il ConstraintMapping come il singolo CM aggiuntivo sembra essere andato nella mia versione di molo 7.

securityHandler.setConstraintMappings(new ConstraintMapping[] {cm}); 

Bar che il mio codice è sostanzialmente identico e funziona per me.

Nota che una volta autenticato il vostro browser non vi chiederà di nuovo a meno che non si riavvia il browser o seguire le istruzioni here

Problemi correlati