Acegi Security: Getting the User Principles

I have currently been working on a project where I wanted to created a custom User object so I could store all the departments in a List <String> that the user is in. I have found Acegi to be great at managing my users role and authentication in my system. I figured that adding department information for the user in the principle object during login would be a great approach since peoples departments would not be changing very quickly.

After I created a new user object that would include a List <String> to hold the department id I had to find a way to easily access this data. To accomplish this I created a helper class which would allow me to get the populated Acegi security object.

A example of a method that I am using to see if a department is in the department list stored in the Acegi User object is below.

  /**
   * This method will accept a department as input and see if the user logged 
   * into the system is in that department.
   * @param dept String Department
   * @return boolean true if user is in department
   */
  public static boolean isUserInDept(String dept)
  {
    // Get the user object and department list
    SecurityContext securityContext = SecurityContextHolder.getContext();
    User acegiUser = (User) securityContext.getAuthentication().getPrincipal();
    List <String> depts = acegiUser.getDepts();
    boolean retValue = false;
    
    // See if the department passed in is in the list of departments
    retValue = depts.contains(dept);
    
    return retValue;
  }

To explain this method further, the ~SecurityContextHolder object is used by Acegi Security to store the security details for the user. The ~SecurityContextHolder uses a ~ThreadLocal to store these details in the application and will be available to all methods in the current execution thread.

So if you want to get the User object in the current execution thread all you need to do is call the following code and then preform logic on it as necessary.

User acegiUser = (User) securityContext.getAuthentication().getPrincipal();

Posted on Nov 07, 2007 by Mike Jennings in Java | 0 Comments | Permalink



Post a Comment:
Comments are closed for this entry.