In Chapter 8, Adding authentication we used so-called memory users, with a list of users in an XML file. When you need a more dynamic list of users, you can use RIFE's support for database users. We'll describe how this differs from memory users somewhat briefly here.
First, we need to make the authentication element extend rife/authenticated/database.xml
instead of memory.xml
. We also need to specify the configuration file for the data source to use. Let's take a look at an example element file:
Example 11.1. Authentication element for database users
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE element SYSTEM "/dtd/element.dtd"> <element extends="rife/authenticated/database.xml"> <property name="template_name">auth</property> <property name="role">admin</property> <property name="datasource"><datasource>postgresql</datasource></property> <submission name="credentials"> <param name="login"/> <param name="password"/> </submission> <childtrigger name="authid"/> </element>
Then you need to create DatabaseUsers
and DatabaseSessions
objects using DatabaseUsersFactory
and DatabaseSessionsFactory
. RIFE comes with support for database users for Oracle, PostgreSQL and MySQL so you don't need to write any code if you use those. Then you call the install
methods of the users and sessions objects, after which authentication works just like for memory users.
The installation of the user and session tables has to be performed before we use them. It can be done, for example, in a separate "setup" subsite where the admin is authenticated as a memory user.
Example 11.2. Installing the tables for database users
Datasource source = Datasources.getRepInstance(). getDatasource(Config.getRepInstance().getString("DATASOURCE")); DatabaseUsersFactory.getInstance(source).install(); DatabaseSessionFactory.getInstance(source).install();
In some cases, you don't want to store session information in the database, even though the users are stored there. That's what the mixed authentication elements is for: rife/authenticated/mixed.xml
. It is used in the same way as the database authentication element, with the exception that the database session object isn't needed since the session data will be stored in memory.
There are variants of the memory, database and mixed authentication elements that automatically purges the session information when it's outdated. They are all prefixed by "purging"
, for example:
<element extends="rife/authenticated/purgingdatabase.xml">
The maximum time a user can be idle before the session is invalidated is controlled by the configuration option SESSION_DURATION
, which defaults to 20 minutes.