是否可以在不执行的情况下检查 Spring Controller 方法的权限?
我的 REST API 的 JS 客户端想知道,是否允许查询某个 URL.使用标准注释在控制器方法上配置权限:
The JS client of my REST API wants to know, is a query to a certain URL permitted or not. Permissions are configured on the controller methods using the standard annotations:
@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"
}
}
对于只读方法,可以对 JS 客户端进行编程以尝试访问 URL 本身,忽略结果并仅查看状态(200 或 403-Forbidden).这在性能方面不是最好的,但至少在功能上是正确的.但是对于 write 方法,我认为没有办法解决.希望这个问题有一个合理的解决方案.
For read-only methods it would be possible to program the JS client to try and access a URL itself, ignore the result and look only on the status (200 or 403-Forbidden). It's not best performance-wise, but at least correct functionally. But for the write method I see no way to work around. Hope there is a sane solution for this problem.
附言感谢@Bogdan 提供的解决方案.这是我需要的方法的全文:
P.S. Thanks to @Bogdan for the solution. This is the full text of the method I need:
@Autowired
WebInvocationPrivilegeEvaluator evaluator;
@RequestMapping("/check")
public String check(String url, Authentication authentication) {
return Boolean.toString(evaluator.isAllowed(url, authentication));
}
对于您发布的 UtilController
,您可以使用类似 WebInvocationPrivilegeEvaluator,也许还可以看看 授权标签有效.
For the UtilController
you posted you could go with something like a WebInvocationPrivilegeEvaluator, maybe also have a look at how the authorize tag works.
此外,根据您在做什么,这样的事情也可以工作:
Additionally, depending on what you are doing, something like this could also work:
@Controller
@RequestMapping("/books")
public class BooksController {
@RequestMapping("read")
@Secured("ROLE_READER")
public ModelAndView read(int id) { ... }
@RequestMapping("canRead")
@Secured("ROLE_READER")
public void canRead() { }
@RequestMapping("write")
@Secured("ROLE_WRITER")
public ModelAndView write(int id, String contents) { ... }
@RequestMapping("canWrite")
@Secured("ROLE_WRITER")
public void canWrite() { }
}
您还可以通过以下方式检查多个角色:
You can also check for multiple roles with:
@RequestMapping("canReadOrWrite")
@Secured({"ROLE_READER", "ROLE_WRITER"})
public void canReadOrWrite() { }
然后您可以检查调用新方法的状态代码.
You can then check the status code for calling the new methods.