Reputation: 2093
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();
Upvotes: 7
Views: 3499
Reputation:
You can do it by adding a context.xml file.
try {
Context context = tomcat.addWebapp("/test", "PathToTheWebApp");
context.setConfigFile(Paths.get("PathToTheContextFile").toUri().toURL());
} catch (ServletException e) {
}
Your context.xml should be like this.
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<Realm className="org.apache.catalina.realm.MemoryRealm" pathname="PathToUsers.xml"/>
</Context>
Your users.xml file is similar to the tomcat-users.xml file. Example:
<?xml version='1.0' encoding='utf-8'?>
<tomcat-users>
<role rolename="admin"/>
<user username="admin" password="admin" roles="admin"/>
</tomcat-users>
Upvotes: 1
Reputation: 2093
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");
Upvotes: 9