DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Pipelines on Fire: Why Your CI/CD Tools Are the New Cyber Battlefield
  • The Agent in Your Pipeline Doesn't Have a Manager. That's the Problem.
  • Treat PII as Toxic: Designing Secure Systems That Contain the Blast Radius
  • Building Trusted, Performant, and Scalable Databases: A Practitioner’s Checklist

Trending

  • AI-Assisted Product Discovery
  • Building Enterprise Authentication with Angular, Spring Boot, SSO, and MFA
  • Building Multi-Rail Payment Failover to Stop Latency Spikes and Double Debits
  • Kafka Consumers on EKS: Designing for a Platform That Restarts Your Consumer Group

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Data Engineering
  3. Databases
  4. Row Level Security in Hibernate Using @Filter

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.

By 
Ali Akbar Azizkhani
·
Dec. 20, 17 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
22.9K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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", );
}
Database Filter (software) Hibernate Software system security

Opinions expressed by DZone contributors are their own.

Related

  • Pipelines on Fire: Why Your CI/CD Tools Are the New Cyber Battlefield
  • The Agent in Your Pipeline Doesn't Have a Manager. That's the Problem.
  • Treat PII as Toxic: Designing Secure Systems That Contain the Blast Radius
  • Building Trusted, Performant, and Scalable Databases: A Practitioner’s Checklist

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook