I am having a simple Java web application with not more than 20-25 users who would be logged in. I am currently using tomcat server to host it and am using the UderDatabaseRealm for access control. I would like to add a feature to this application wherein the administrator can add users to the system through the application itself. I would like to know is it possible to programmatically add users to this file. One method I can think of is to open the tomcat_users.xml file within my application and do XML manipulation to add the users. Is there a better way than this?
My realm is configured in servers.xml as :-
<Realm className="org.apache.catalina.realm.LockOutRealm">
<!-- This Realm uses the UserDatabase configured in the global JNDI
resources under the key "UserDatabase". Any edits
that are performed against this UserDatabase are immediately
available for use by the Realm. -->
<Realm className="org.apache.catalina.realm.UserDatabaseRealm" resourceName="UserDatabase"/>
</Realm>
My tomcat_users.xml file is as follows:-
<tomcat-users>
<role rolename="admin"/>
<role rolename="local"/>
<user username="tomcat" password="tomcat" roles="admin"/>
</tomcat-users>
In terms of your original question, Tomcat reads tomcat-users.xml at startup and would not pick up any changes that were made to the file itself while the server is running. You would need to use JMX to interact with the
UserDatabaseRealm
MBean if you wanted to make changes dynamically at runtime.The better option is almost certainly to switch to using a DataSourceRealm, as the earlier answer suggested.
You can use something more flexible: a database. You need to configure a
org.apache.catalina.realm.DataSourceRealm
.DB:
server.xml
:context.xml
:See full examples in http://wiki.apache.org/tomcat/TomcatDataSourceRealms and http://java.dzone.com/articles/setting-apache-tomcat-basic
Here is a JSP example of how to add new users to the tomcat: first update the
server.xml
file, addreadonly="false"
attribute for the resourceauth="Container"
:then in a jsp file:
you can also change the password of a user see my answer: How to change a user's tomcat password in servlet application
You can use JNDI to get the UserDatabase Object from your running tomcat with all information about your users and roles. You have to define your UserDatabase as global resource in your server.xml and add a resource link to your context.xml file like this:
server.xml
context.xml of your webapp
Now you can use the InitialContext to get the UserDatabase Object:
Now you can call methods of this Database like :
Don't forget to call the
ud.save();
method so that the changes can be written to the xmlfile. To save this, the readonly attribute of the global resource has to be false.Another alternative is to use JMX as suggested by the Tomcat documentation. The following links will be probably helpful.
But as Paul Vargas said using a DataSourceRealm will be a much easier solution in this case.