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
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • How Trustworthy Is Big Data?
  • PostgreSQL 12 End of Life: What to Know and How to Prepare
  • Data Privacy and Security: A Developer's Guide to Handling Sensitive Data With DuckDB
  • Using AUTHID Parameter in Oracle PL/SQL

Trending

  • Apple and Anthropic Partner on AI-Powered Vibe-Coding Tool – Public Release TBD
  • Code Reviews: Building an AI-Powered GitHub Integration
  • Using Java Stream Gatherers To Improve Stateful Operations
  • Advancing Your Software Engineering Career in 2025
  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 user avatar
Ali Akbar Azizkhani
·
Dec. 20, 17 · Tutorial
Likes (12)
Comment
Save
Tweet
Share
22.2K Views

Join the DZone community and get the full member experience.

Join For Free

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

  • How Trustworthy Is Big Data?
  • PostgreSQL 12 End of Life: What to Know and How to Prepare
  • Data Privacy and Security: A Developer's Guide to Handling Sensitive Data With DuckDB
  • Using AUTHID Parameter in Oracle PL/SQL

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!