I am currently working on a Spring-based Neo4j (a graph database) application and needed to add user authentication. Since Spring Security allows integrating custom authentication providers it felt only natural to implement a provider based on Neo4j. A data structure to support users and groups is already provided in the Neo4j Wiki. I used it as the basis for my implementation with some wrapping so it could be integrated with Spring Security and provides administrative methods.

When you take a look at the data structure you will see how suitable a graph is to store user data. It allows you to easily create a hierarchical group structure and in order to aggregate all of the user’s groups just need to traverse (find one or more paths) from the user node to the start node.

Implementation

Only three pieces are really needed once you have the required components such as Neo4j and Spring Security included in your project:

  1. Define an interface that defines ways to manipulate the users and groups: AuthenticationService.java (actually I needed this only because of some JDK proxying issues, but it never hurts to have an interface)
  2. An implementation of the user service interface for Neo4j: NeoBasedUserService.java
  3. Integration of the authentication provider in your context: app-security.xml

NB: The “GrantedAuthority” objects in the Spring nomenclature are implemented here simply as groups.

The interface and implementation provide the bare minimum of what I needed for the application. Still, the interface is well defined and reasonably well tested, so don’t be afraid to give it a try.