Nov 1, 2018

How to achieve flexibility in JDBC Realms in Glassfish

In many Java EE applications declarative security is required where user and group information is stored in a database. To support this, an application server must support a security realm based on a JDBC datasource.

Glassfish application server also supports a configuration like this through the JDBCRealm. 

Unfortunately, this JDBCRealm is restrictive in various ways:
  • It assumes a data model where groups are modelled as value objects. Specifically, if a group should have more properties apart from its name, then this should be modeled in a different database structure with the group name as a key.
  • A very specific data model is assumed. Two tables are used: One with for every user the encoded password and another with pairs of usernames and groupnames to define to which groups a user belongs.
  • It is static in that it assumes that a user will always be a part of the same groups over time. After retrieving the groups for the first time, it caches them indefinitely (performance gain!). This makes the JDBCRealm of glassfish unsuitable for dynamic applications where users can join or leave groups.
If the JDBCRealm suits your needs, you can just use it. If not, then you have to work around it.

A quick solution is to use database view. By creating views from your existing database tables and point your JDBCRealm to those views instead of tables, you can make use of  JDBCRealm directly.

Another solution is to use Custom Realm. You can use a custom realm provided by third party, such as FlexibleJdbcRealm. Or for maximum flexibility, such as includes openid authorization with your existing server authorization, you have to create your own custom realm.