How to handle authentication/authorization with users in a database?

There are several options. Which to choose is fully up to you. Just objectively weigh the concrete advantages and disadvantages conform your own situation.


1. Use Java EE provided container managed authentication

Just declare a <security-constraint> in web.xml which refers a security realm which is configured in servletcontainer. You can for your webapp specify URL pattern(s) which should be checked for login and/or role(s), e.g. /secured/*, /app/*, /private/*, etc.

Before Java EE 8, you unfortunately still need to configure a security realm in a servletcontainer-specific way. It’s usually described in servletconainer-specific documentation. In case of Tomcat 8, that’s the Realm HOW-TO. For example, a database based realm based on users/roles tables is described in section “JDBCRealm”.

Since Java EE 8, there will finally be a standard API based on JSR-375.

Advantages:

  • Relatively quick and easy to setup and use.
  • Since Java EE 8 there’s finally a robust and flexible standard API.

Disadvantages:

  • Before Java EE 8, realm configuration is container-specific. In Java EE 8, the new JSR-375 Security Spec should solve that with help of JASPIC.
  • Before Java EE 8, , there is no fine grained control.
  • Before Java EE 8, it’s very spartan; no “remember me”, poor error handling, no permission based restriction.

See also:


2. Homegrow a servlet filter

This allows for much more fine grained control, but you’re going to need to write all the code yourself and you should really know/understand how you should implement such a filter to avoid potential security holes. In JSF side, you could for example just put the logged-in user as a session attribute by sessionMap.put("user", user) and check in the filter if session.getAttribute("user") is not null.

Advantages:

  • Fine grained control.
  • Completely container independent.

Disadvantages:

  • Reinvention of the wheel; new features require a lot of code.
  • As starter, you’re never sure if your code is 100% robust.

See also:


3. Adapt a 3rd party framework

For example, Apache Shiro, Spring Security, etc. This offers usually much more fine grained configuration options than standard container managed authentication and you don’t need to write any code for this yourself, expect of the login page and some (XML) configuration of course.

Advantages:

  • Fine grained control.
  • Completely container independent.
  • No reinvention of the wheel; minimum of own code.
  • Thoroughly developed and tested by lot of users, so most likely 100% robust.

Disadvantages:

  • Some learning curve.

See also:

Leave a Comment