Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Row Level Security in Hibernate Using @Filter

DZone's Guide to

Row Level Security in Hibernate Using @Filter

Learn how to give certain people permission to view certain parts of your database, and thus increase your database's security.

· Security Zone ·
Free Resource

Mobile is increasingly becoming a part of every consumers’ identity, but the increasing use of this digital channel is escalating the security risks faced by consumers and institutions.

One of the topics that you will most often find with software systems is the access of user to data. For almost six years, I have been working in the authorization of data to users in products.

In our company, we produce systems that have different users with different roles, each based on the logic of specific access to the data they are looking for. For example, consider that we have an organization that uses our software system to manage employees. This organization has a very large structure, and users in this system within HR should keep staffing information up-to-date. On the other hand, the role of the Director General of Human Resources should be able to see all the personnel in the organization. To do this, we made it so each user had to determine their level of access to the structure of the organization. We ended up with the class diagram below.

Image title

Now, each user of the system has access to an organization. Basically, the above figure shows that any given employee in an organization is working. Next, it became necessary to view every user of this system. Here it should be noted that we used Hibernate to persist the information in the database, so the classes are set as follows.

User.java

@Entity
@Table(name = "APP_USER")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    Long id;

    @Column
    String username;

    @Column
    String password;

    @ManyToMany
    @JoinTable(name = "APP_USER_ORGANIZATION",
            joinColumns = {@JoinColumn(name = "USER_ID")},
            inverseJoinColumns = {@JoinColumn(name = "OEG_ID")})
    List<OrganizationStructure> organizationStructures;
}

OrganizationStructure.java 

@Entity
@Table(name = "APP_ORGANIZATION_STRUCTURE")
public class OrganizationStructure {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    Long id;

    @Column(name = "DEPARTMENT_NAME")
    String departmentName;

    @ManyToOne
    @JoinColumn(name = "PARANT_ID")
    OrganizationStructure parent;

    @OneToMany
    List<OrganizationStructure> childs;

    @OneToMany
    List<Employee> employeeList;

}

 Employee.java

@Entity
@Table(name = "APP_EMPLOYEE")
public class Employee {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    Long id;

    @Column
    String firstname;

    @Column
    String lastname;

    @Column
    String code;

    @ManyToOne
    @JoinColumn(name = "ORG_ID")
    OrganizationStructure organizationStructure;

    @OneToMany
    List<Job> jobList;
}

Below is the implementation pattern for the layers of the same standard layers. Consider which methods should be written for employees to read the data.

public interface EmployeeRepositoy {
    Employee findById (Long id,);
    List <Employee> findByOrganizationId (Long orgId);
    List <Employee> allEmployee ();
}

As we see in the above methods, the list or employee is supposed to be returned as output. If you need to write an equivalent hql for these methods, it will look as follows:

@Query ("select e from Employee e where e.organizationStructure.id in (select os.id from User u join u.organizationStructures os where u.id =? # {principal? .id}) ")
Employee findById (Long id);

And, therefore, EmployeeRepository should look like this:

public interface EmployeeRepositoy {

    @Query("select e " +
            "from Employee e " +
            "where e.id=?1 and  e.organizationStructure.id in (select os.id from User u join u.organizationStructures os where u.id=?#{ principal?.id })")
    Employee findById(Long id);

    @Query("select e " +
            "from Employee e " +
            "where e.organizationStructure.id=?1 and  e.organizationStructure.id in (select os.id from User u join u.organizationStructures os where u.id=?#{ principal?.id })")
    List<Employee> findByOrganizationId(Long orgId);

    @Query("select e " +
            "from Employee e " +
            "where e.organizationStructure.id in (select os.id from User u join u.organizationStructures os where u.id=?#{ principal?.id })")
    List<Employee> allEmployee();
}

If you are careful, the following section is repeated in all your queries:

 e.organizationStructure.id in (select os.id from User u join u.organizationStructures os where u.id =? # {principal? .id})

All the examples like the class above have no three methods. It may be a class that has many methods. The first question is, how to solve this problem?

The Following Methods Seem to Be Feasible

1. Use @Where:

This method has both good and bad qualities. This method adds this filter to the query in all queries. However, it may not be necessary to perform this filter in all modes. Another problem is the impossibility of using the parameter in this method. Parameters may be required to apply this logic, which does not allow this. The good thing about this method is that it does not need to be active or disabled, and it's easy to apply

@Entity
@Table(name = "APP_EMPLOYEE")
@Where(condition = " ORG_ID in (select os.ORG_ID from APP_USER u join APP_USER_ORGANIZATION os on os.User_Id=u.id where u.id=:userId)")
public class Employee {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    Long id;

    @Column
    String firstname;

    @Column
    String lastname;

    @Column
    String code;

    @ManyToOne
    @JoinColumn(name = "ORG_ID")
    OrganizationStructure organizationStructure;

    @OneToMany
    List<Job> jobList;
}

2. Define a Class-Level Variable and Concatenate With a Query

The problem with this method is that the developer may for some reason forget to concatenate the clause into his query. Another problem is that it is likely that another programmer will execute a query on this model. In this case, it is not guaranteed that this filter will be applied.

public interface EmployeeRepositoy {


    final String authorizeQuery="e.organizationStructure.id in (select os.id from User u join u.organizationStructures os where u.id=?#{ principal?.id })";

    @Query("select e " +
            "from Employee e " +
            "where e.id=?1 and " +authorizeQuery)
    Employee findById(Long id);

}

3. Use @Filter

This approach is one of the most reliable methods. By using the feature provided by Hibernate, it can be defined by defining a filter and activating it at the session level, ensuring that all queries run if they are implemented. The filter is at the model level, thus this filter will apply to the surface of the model. For example:

@Entity
@Table(name = "APP_EMPLOYEE")
@FilterDef(name="authorize", parameters={@ParamDef( name="userId", type="long" )})
@Filter(name = "authorize" ,condition = " ORG_ID in (select os.ORG_ID from APP_USER u join APP_USER_ORGANIZATION os on os.User_Id=u.id where u.id=:userId)")
public class Employee {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    Long id;

    @Column
    String firstname;

    @Column
    String lastname;

    @Column
    String code;

    @ManyToOne
    @JoinColumn(name = "ORG_ID")
    OrganizationStructure organizationStructure;

    @OneToMany
    List<Job> jobList;
}

Each time, it executes the query, we can apply this code:

@Inject
Session session ;

public Employee find(Long empId) {
  applyDafaultAuthorizeFilter(session);
  String hql="select e from Employee e where e.id=:empId"
  Query query =  = session.createQuery(hql);
  query.setParameter("empId",empId);
  return (Employee) query.uniqueResult();
}

public void applyDafaultAuthorizeFilter(Session session) {
  Filter filter = session.enableFilter("authorize");
  filter.setParameter("userId", );
}

Explore the authentication advancements that are designed to secure accounts and payments—without overburdening consumers with a friction-laden experience.

Topics:
hibernate ,security ,authorization ,database security

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}