Class SecurityUtil

java.lang.Object
tech.lastbox.lastshield.security.core.SecurityUtil

@Component public class SecurityUtil extends Object
Utility class for various security-related operations, such as retrieving user roles and authorities, locating user repositories, and interacting with user entities via reflection.

This class provides methods to:

  • Obtain the user repository class annotated with UserHandler.
  • Find users by username using reflection to invoke repository methods.
  • Retrieve user roles and convert them to granted authorities for Spring Security.
  • Handle class loading and reflection for user repository discovery and user entity interaction.
  • Constructor Details

    • SecurityUtil

      public SecurityUtil()
      Default constructor for the SecurityUtil class. This constructor is used to instantiate the SecurityUtil utility class.
  • Method Details

    • getUserRepositoryClass

      public Class<?> getUserRepositoryClass()
      Retrieves the class of the user repository annotated with UserHandler. This method performs classpath scanning to find classes annotated with UserHandler and returns the corresponding class for the user repository. The class is expected to have a method to retrieve users by their username.

      If advanced filtering is enabled (via AdvancedFilterChecker), it will scan the classpath for the appropriate class and return it. If no such class is found, it throws an exception.

      Returns:
      the user repository class annotated with UserHandler.
      Throws:
      RuntimeException - if no user handler class is found or if an error occurs during class loading.
    • getUserAuthorities

      public List<org.springframework.security.core.GrantedAuthority> getUserAuthorities(Object user)
      Converts the user's roles to a list of GrantedAuthority objects. This method is used to convert the user's roles (usually from a field like "roles" or "role") into a list of GrantedAuthority, which Spring Security uses to manage access control.
      Parameters:
      user - the user object from which roles will be extracted.
      Returns:
      a list of GrantedAuthority representing the user's roles.
    • findUserByUsername

      public Object findUserByUsername(Object userService, String username)
      Finds a user by their username by invoking the "findUserByUsername" method on the provided user repository. The method uses reflection to dynamically invoke the appropriate method on the user repository to retrieve the user associated with the given username.
      Parameters:
      userService - the user repository or service to search for the user.
      username - the username of the user to search for.
      Returns:
      the user entity associated with the given username.
      Throws:
      RuntimeException - if the "findUserByUsername" method is not found or if an error occurs during invocation.