I have an endpoint secured with token given in the header. I would like to create my custom annotation so when I annotate the controller method the validation token goes first and then if the token was accurate do the rest of the method. I tried do it with interceptor and it worked but I want to do it using reflection to have custom annotation. I can share some of my code snippet but there is not a lot of code because I couldn't find some that tells me how to get token from header and validate it. And I'm a noob in reflection.
Custom Annotation
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface TokenValidation {
String token() default "";
}
Controller Class
@TokenValidation
@PostMapping("/endpoint")
public ResponseEntity createComplianceDirectory(@RequestBody ComplianceDirRequest request) {
return ResponseEntity.status(HttpStatus.OK).build();
}
Reflection class
@Value("${token}")
private String token;
private Reflections reflections;
public Reflection() {
reflections = new Reflections(new ConfigurationBuilder().setUrls(ClasspathHelper.forPackage("com.sampleapp.controller"))
.setScanners(new FieldAnnotationsScanner()));
setReflections();
}
public void setReflections() {
Set<Method> methods = reflections.getMethodsAnnotatedWith(TokenValidation.class);
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
if (requestAttributes instanceof ServletRequestAttributes) {
HttpServletRequest request = ((ServletRequestAttributes)requestAttributes).getRequest();
String requestToken = request.getHeader("Authorization");
}
}
Could someone tell me:
- How to register that reflection class in spring boot to be invoked when the controller method is called.
- Is it a good way in my reflection class to retrieve the header ?
Aucun commentaire:
Enregistrer un commentaire