我创建了一个名为 @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))")
这就是我解决这个问题的方法。
@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();
}
}