Custom Annotation To Handle Authorisation In Spring Boot AOP Tutorial

Custom Annotation To Handle Authorisation In Spring Boot AOP Tutorial


  • Creating custom annotation
  • Creating component in spring boot
  • Creation a configuration and middleware in spring boot
  • Basic of Aspect and usage in spring boot

What is Aspect In Spring Boot ?

Aspects are cross cutting concerns like logging,security in different layers for the ease of code maintenance .

Key Dependency required

  • Spring AOP provides basic AOP Capabilities.
  • AspectJ provides a complete AOP framework.
  • STEP 1 : Lets create an annotation

@Target(ElementType.METHOD) // can use in method only.
public @interface Authorized {

  public boolean enabled() default true;


@Retention(RetentionPolicy.RUNTIME) : instruct compiler to retain the annotation during runtime
@Target(ElementType.METHOD) : this suggest where this annotation can be used

  • Step 2 : Lets Create a file which actually implement logic of authorization

public class AuthorizationImpl { 
    public boolean authorize(String token) {
        // implemnt jwt or any any token based authorization logic
        return true;
  • Step 3 Aspect file which acts as middleware which intercept the the request and authorize and proceed

public class AuthAspect {
   AuthorizationImpl authBean;
   @Before("@annotation(com.<packagepath>.Authorized) && args(request,..)")
   public static void before(HttpServletRequest request){
       if (!(request instanceof HttpServletRequest)) {
           new RuntimeException("request should be HttpServletRequesttype");
           "session information which cann be acces in controller"
       }else {
            throw new RuntimeException("auth error..!!!");
  • Step 3 : Usage of the annotation to authorize the request

@RequestMapping(path = "/activities-to-jobs",
        produces = {APPLICATION_JSON_VALUE},
        headers = {"Authorization"})
public class XxxxController {
   @RequestMapping(path = "/{id}/note", method = RequestMethod.GET)
   public opDTO getSomeResult(HttpServletRequest request,....){