Search code examples
javaspring-bootannotationsspring-el

Can I set value from custom annotation to @PreAuthorize in Spring


I have created an annotation called @AllowAccessTo as follows,

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@PreAuthorize("hasAnyAuthority(@authorityService.getPrivilege(need to inject value form allowaccess annotation))")
public @interface AllowAccessTo {
    String value() default "";
}

In my Rest Controller, I have annotated that custom annotation.

@RestController
@RequestMapping("/api")
public class FooEndpoint {

    @GetMapping("/students")
    @AllowAccessTo("GET_ALL_STUDENT")
    public List<Student> getAllStudents() {
        return students;
    }
}

What I want to do is, I need to inject that "GET_ALL_STUDENT" value to

@authorityService.getPrivilege({{value from custom annotation}})
@PreAuthorize("hasAnyAuthority(@authorityService.getPrivilege(value form AllowAccessTo annotation))")


Solution

  • This is how I solve this.

    @Target({ElementType.METHOD, ElementType.TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    @PreAuthorize("@securityHandler.check")
    public @interface AllowAccessTo {
        String value() default "";
    }
    
    @Service("securityHandler")
    @Slf4j
    public class SecurityHandler {
    
        @Autowired
        private HttpServletRequest httpServletRequest;
    
    
        public boolean check() {
            try {
                log.debug("checking permission based on jwt");
                List < KseRoleDto > kseRoles = new ArrayList < > ();
                String accessCode = checkAllowAccess();
                // check permission with access code
                if (hasPermission) {
                    return true;
                } else {
                    return false;
                }
            } catch (Exception e) {
                log.error("permission not matched and exception occurred", e);
                return false;
            }
        }
    
        public String checkAllowAccess() {
            HandlerMethod attribute = (HandlerMethod) httpServletRequest.getAttribute(HandlerMapping.BEST_MATCHING_HANDLER_ATTRIBUTE);
            GrantEndpoint methodAnnotation = attribute.getMethodAnnotation(GrantEndpoint.class);
            return methodAnnotation.value();
        }
    
    }