我可以在Spring中将自定义注释的值设置为@PreAuthorize

问题描述 投票:0回答:1

我创建了一个名为 @AllowAccessTo 的注释,如下所示,

@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 "";
}

在我的 Rest 控制器中,我已经注释了该自定义注释。

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

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

我想做的是,我需要将“GET_ALL_STUDENT”值注入

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

java spring-boot annotations spring-el
1个回答
1
投票

这就是我解决这个问题的方法。

@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();
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.