Custom Annotation To Handle Authorisation In Spring Boot

Ashrith g.n
2 min readMay 24, 2019

--

Overview:

  • Creating custom annotation
  • Creating component in spring boot
  • Creation a configuration and middle ware 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

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>5.0.1.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.12</version>
<scope>compile</scope>
</dependency>
  • Spring AOP provides basic AOP Capabilities.
  • AspectJ provides a complete AOP framework.

STEP 1 : Lets create an annotation

@Retention(RetentionPolicy.RUNTIME)
@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 authorisation
@Component
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 middle ware which intercept the the request and authorise and proceed
@Aspect
@Configuration
public class AuthAspect {
@Autowired
AuthorizationImpl authBean;

@Before("@annotation(com.<packagepath>.Authorized) && args(request,..)")
public void before(HttpServletRequest request){
if (!(request instanceof HttpServletRequest)) {
throw
new RuntimeException("request should be HttpServletRequesttype");
}

if(authBean.authorize(request.getHeadr("Authorization"))){
req.setAttribute(
"userSession",
"session information which cann be acces in controller"
);
}else {
throw new RuntimeException("auth error..!!!");
}

}

}
  • Step 3 : Usage of the annotation to authorize the request
@RestController
@RequestMapping(path = "/activities-to-jobs",
produces = {APPLICATION_JSON_VALUE},
headers = {"Authorization"})
public class XxxxController {
@RequestMapping(path = "/{id}/note", method = RequestMethod.GET)
@Authorized
public opDTO getSomeResult(HttpServletRequest request,....){

}
}

Originally Published @https://blogs.ashrithgn.com/2018/07/19/custom-authorization-annotation/

Custom Annotation To Handle Authorisation In Micronaut AOP Tutorial (ashrithgn.com)

--

--