我的 REST API 的 JS 客户端想知道,是否允许查询某个 URL。使用标准注释在控制器方法上配置权限:
@Controller
@RequestMapping("/books")
public class BooksController {
@RequestMapping("read")
@Secured("ROLE_READER")
public ModelAndView read(int id) { ... }
@RequestMapping("write")
@Secured("ROLE_WRITER")
public ModelAndView write(int id, String contents) { ... }
}
@Controller
@RequestMapping("/util")
public class UtilController {
@RequestMapping("check")
public String check(String url) {
//if url is "/books/read" and isUserInRole("ROLE_READER")
//or url is "/books/write" and isUserInRole("ROLE_WRITER")
//return "true", otherwise "false"
}
}
Run Code Online (Sandbox Code Playgroud)
对于只读方法,可以对 JS 客户端进行编程以尝试访问 URL 本身,忽略结果并仅查看状态(200 或 403-Forbidden)。这在性能方面不是最好的,但至少在功能上是正确的。但是对于 write 方法,我认为没有办法解决。希望有一个理智的解决方案来解决这个问题。
PS 感谢@Bogdan 提供的解决方案。这是我需要的方法的全文:
@Autowired
WebInvocationPrivilegeEvaluator evaluator;
@RequestMapping("/check") …Run Code Online (Sandbox Code Playgroud)