bookmark_borderAspect Oriented Programming for authorization in Spring

Spring AOP, or Aspect-Oriented Programming, is a framework within the Spring Framework that enables modularization of cross-cutting concerns in Java applications. It allows developers to separate concerns like logging, security, and transaction management from the core business logic. AOP achieves this by introducing aspects, which are modules encapsulating cross-cutting concerns, and weaving them into the application at specified points. This helps in achieving better code modularity, reusability, and maintainability by reducing code duplication and promoting a cleaner architecture.

In this article we will show you how to utilize AOP for authorization.

This is a database table which contains products:

1Product 1402
2Product 2502
3Product 32010

ProductService class contains a method for product deletion:

This service method is exposed trough REST API call which accepts ID parameter and calls the method which deletes product.

JWT of authenticated user contains its own tenant ID which is 2 in current example. So user should only be allowed to delete product 1 and product 2. Deletion attempt of product 3 should generate 403 forbidden.

We will create an annotation which should be placed before each protected method.

Next class we need is an aspect

Finally we are going to annotate a protected method from service

Order of actions

  • @ProductPermission annotation triggers ProductPermissionAspect.check method execution before each call of annotated method
  • ProductPermissionAspect grabs first parameter of a target method call which is product ID
  • ProductPermissionAspect checks if the product belongs to tenant of an authenticated user
  • ProductPermissionAspect generates 403 forbidden if the product doesn’t belong to the user

If you want to deep dive into more details: