簡體   English   中英

我可以在Spring中將自定義注釋的值設置為@PreAuthorize嗎

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

我創建了一個名為 @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 Controller 中,我已經對該自定義注釋進行了注釋。

@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))")

這就是我解決這個問題的方法。

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

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM