Basic Authentication with embedded Jetty 7 server and no web.xml file

匆匆过客 提交于 2019-12-09 15:55:48

问题


I have an embedded implementation of Jetty 7 running as a service and want to add basic authentication with no web.xml file for a servlet.

I created my credentials using the steps described here

I thought that I could create the server, create a security handler with basic authentication and attach a HashLoginService to the security manager. But I am clearly missing several things because I am never getting prompt for credentials.

Below is the code. Any help would be greatly appreciated.

    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;
}

回答1:


I got this working and posted a sample webapp here




回答2:


The code looks broadly ok. My interface is slightly different for adding the ConstraintMapping as the single CM add seems have gone in my version of jetty 7.

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

Bar that my code is basically identical and does work for me.

Note that once authenticated your browser will not prompt you again unless you restart your browser or follow the instructions here



来源:https://stackoverflow.com/questions/8056851/basic-authentication-with-embedded-jetty-7-server-and-no-web-xml-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!