Skip to content

Instantly share code, notes, and snippets.

@n-shinya
Created April 17, 2013 04:57
Show Gist options
  • Save n-shinya/5401893 to your computer and use it in GitHub Desktop.
Save n-shinya/5401893 to your computer and use it in GitHub Desktop.
Basic authentication with embedded tomcat(埋め込みTomcatでBASIC認証する)

Basic authentication with embedded tomcat(埋め込みTomcatでBASIC認証する)

tomcat-users.xml

<?xml version='1.0' encoding='utf-8'?>
<tomcat-users>
  <role rolename="admin"/>
  <user username="user" password="pass" roles="admin"/>
</tomcat-users>

code

public class EmbeddedTomcat

    private static Tomcat tomcat = new Tomcat(); 

    private static final String AUTH_ROLE = "admin";

    public void startTomcat() {

            tomcat.setBaseDir("tomcat");
            Context ctx = tomcat.addWebapp("/", "sample.war");
            tomcat.setHostname("localhost");
            tomcat.setPort(8080);

            LoginConfig config = new LoginConfig();
            config.setAuthMethod("BASIC");
            ctx.setLoginConfig(config);
            ctx.addSecurityRole(AUTH_ROLE);
            SecurityConstraint constraint = new SecurityConstraint();
            constraint.addAuthRole(AUTH_ROLE);
            SecurityCollection collection = new SecurityCollection();
            collection.addPattern("/*");
            constraint.addCollection(collection);
            ctx.addConstraint(constraint);
            
            String path = "/path/to/tomcat-users.xml";
            MemoryRealm realm = new MemoryRealm();
            realm.setPathname(path);
            tomcat.getEngine().setRealm(realm);

            tomcat.start();
    }
}
Copy link

ghost commented Mar 7, 2015

Very helpful. Thanks. Is there a way to also add access logs to embedded tomcat? (maybe through adding an AccessLogValve?)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment