我可以在Spring中设置自定义注释的值为@ preauthorization吗?



我创建了一个名为@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();
}
}

相关内容

  • 没有找到相关文章

最新更新