How to add a custom security annotation to Spring MVC controller method

We also created a custom annotation in our project. What you need to accomplish this, is a bit of Aspect Oriented Programming.

First you'll want to create your own annotation to tag your methods, as follows:

public @interface CustomSecurityAnnotation {
}

Then you have to write the logic which is triggered when your method is executed. You write an aspect for that.

@Aspect
@Component
public class CustomSecurityAspect {
    @Pointcut("@annotation(my.package.CustomSecurityAnnotation)")
    private void customSecurityAnnotation() {
    }

    @Around("my.package.CustomSecurityAspect.customSecurityAnnotation()")
    public Object doSomething(ProceedingJoinPoint pjp) throws Throwable {
        HttpServletRequest req = getRequest();
        // Check header values
        // Throw Spring's AccessDeniedException if needed
        return pjp.proceed();
    }

    private HttpServletRequest getRequest() {
        ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return sra.getRequest();
    }
}

As you can see, I've already included a method to retrieve the current HTTP request so you can easily retrieve the header you want to check.

In case of an AccessDeniedException, Spring automatically sets the response status code to HTTP 403.

Don't forget to enable @EnableAspectJAutoProxy on your @Configuration class to enable aspects.