Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to programatically add users to tomcat UserDatabaseRealm?

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>
like image 282
avimonk Avatar asked Dec 25 '22 02:12

avimonk


1 Answers

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

<GlobalNamingResources>

     <Resource auth="Container" description="User database that can be updated and saved"
        factory="org.apache.catalina.users.MemoryUserDatabaseFactory" name="UserDatabase"
        pathname="/home/user/tomcat-users.xml" type="org.apache.catalina.UserDatabase"
        readonly="false" />

</GlobalNamingResources>

<Realm className="org.apache.catalina.realm.LockOutRealm">

    <Realm className="org.apache.catalina.realm.UserDatabaseRealm" resourceName="UserDatabase"/>

</Realm>

context.xml of your webapp

<Context>

    <ResourceLink name="UserDatabase" global="UserDatabase"
        type="org.apache.catalina.UserDatabase" />

</Context>

Now you can use the InitialContext to get the UserDatabase Object:

UserDatabase ud = (UserDatabase) new InitialContext().lookup("java:comp/env/UserDatabase");

Now you can call methods of this Database like :

ud.createUser("username", "password", "fullname");

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.

like image 55
Patrick Lindner Avatar answered Jan 20 '23 00:01

Patrick Lindner