Jardo Jardo -4 years ago 117
Java Question

How to define tomcat-users.xml on embedded Tomcat?

I'm using Selenium to run automatic JUnit tests on a Maven web application. Basically I'm running the application on an embedded Tomcat server (org.apache.tomcat.embed). The application uses BASIC authentication, so I need to somehow define tomcat-users.xml on the embedded tomcat server. I tried putting tomcat-users.xml to src/main/webapp/META-INF/ but it doesn't work.

Here's how I start the server:

tomcat = new Tomcat();
tomcat.setPort(0);
tomcat.addWebapp("/", new File("src/main/webapp/").getAbsolutePath());
tomcat.start();

Answer Source

I figured this out some time ago so here's the solution for someone who has a similar problem. Basically you can define the things that would be in tomcat-users.xml directly in the java code:

//Add role and user order is important
tomcat.addRole("userName", "admin");
tomcat.addRole("userName", "editor");
tomcat.addUser("userName", "password");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download