Auditing infrastructure for your app using Spring AOP, Custom annotations and Reflection

The next post will demonstrate how to write simple auditing using Spring AOP and annotations. the auditing mechanism will be clean, efficient and easy to maintain. (and Kewwl;P).

 

I will demonstrate my example on a User management system(I assume you have general knowledge on reflection and AOP).

 

We start with simple DB table to hold our auditing data

 `id`,
 `username`
 `user_type`
 `action`
 `target_user`
 `date`
 `user_ip`

We need to populate 4 main fields(Username, UserType, Action, TargetUser)

*Username – the user who performs the action

*TargetUser – Target user the action is performed.

 

Now let’s create new annotation to mark our wanna-be-audit method. We going to be very “creative” and use: @AuditAble

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD,ElementType.TYPE})
public @interface Auditable {
AuditingActionType actionType();
}

Annotated @AuditAble method example:


@Override
 @Transactional
 @Auditable(actionType = AuditingActionType.INTERNAL_USER_REGISTRATION)
 public void createInternalUser(UserDTO userDTO) {
 userCreationService.createInternalUserOnDB(userDTO);

}

 

Our future Aspect (aop) will collect some auditing data from the method param’s using DTO’s. In our case the target username and the actionType will be collected as our auditing info.

For that I created another annotation AuditingTargetUsername:

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.TYPE})
public @interface AuditingTargetUsername {
String value() default "";
}

So inside UserDTO we got:


public abstract class UserDTO implements Serializable {

 @NotNull
 @AuditingTargetUsername
 private String userName;

...

}

We annotated the userName with @AuditingTargetUsername. That information will be collected later on.

Now let’s create our AOP’s aspect. Here all the auditing logic is collected and performed(Intercepting @Auditable methods, Extracting information from annotations, Using repository to save the final auditing record)


@Aspect
public class AuditingAspect {

....

@After("@annotation(auditable)")
 @Transactional
 public void logAuditActivity(JoinPoint jp, Auditable auditable) {
 String targetAuditingUser;
 String actionType = auditable.actionType().getDescription();

 String auditingUsername = Authentication auth = SecurityContextHolder.getContext().getAuthentication().getName()
 role = userService.getCurrentUser(false).getPermissionsList().toString();
 auditingUsernameIp = request.getRemoteAddr();
 }
 logger.info(
 "Auditing information. auditingUsername=" + auditingUsername + ", actionType=" + actionType + ", role=" + role + ", targetAuditingUser="
 + targetAuditingUser + " auditingUsernameIp=" + auditingUsernameIp
 );
 auditingRepository
 .save(new AuditingEntity(auditingUsername, role, actionType, targetAuditingUser, auditingUsernameIp,
 new Timestamp(new java.util.Date().getTime())));
 }

ill explain the main code areas:

Pointcut – all @Auditable.annotations
Advice – Type @After (We want to audit after the method is invoked)

ActionType value is retrieved via the annotated method’s declaration:

@Auditable(actionType = AuditingActionType.INTERNAL_USER_REGISTRATION)

auditingUsername is the current user who perform the action(In our case the logged in user). I retrieve that via SecurityContext(Spring Security)

Now we will extract the @targetAuditingUser field via reflection on runtime:


targetAuditingUser = extractTargetAuditingUser(jp.getArgs());
...

public String extractTargetAuditingUserFromAnnotation(Object obj) {
...
 result = getTargetAuditingUserViaAnnotation(obj);

...

}

Thats the logic to extract the annotated fields via reflection:


private String getTargetAuditingUserViaAnnotation(Object obj) {
class cl=obj.getClass()
 String result = null;
 try {
 for (Field f : cl.getDeclaredFields())
 for (Annotation a : f.getAnnotations()) {
 if (a.annotationType() == AuditingTargetUsername.class) {
 f.setAccessible(true);
 Field annotatedFieldName = cl.getDeclaredField(f.getName());
 annotatedFieldName.setAccessible(true);
 String annotatedFieldVal = (String) annotatedFieldName.get(obj);
 logger.debug("Found auditing annotation. type=" + a.annotationType() + " value=" + annotatedFieldVal.toString());
 result = annotatedFieldVal;
 }
 }
 } catch (Exception e) {
 logger.error("Error extracting auditing annotations from obj" + obj.getClass());
 }
 return result;
 }

Result on DB:

audit1

Thats it. we got clean auditing infrastructure all you need is to annotate your method with @Auditable and annotate inside your DTO’s/Entities the desired information to be audited.

 

Idan.


Related Articles:

(23986)