是否可以在不执行的情况下检查Spring Controller方法的权限?

时间:2014-11-30 13:37:42

标签: java spring security rest spring-security

我的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"
  }
}

对于只读方法,可以对JS客户端进行编程以尝试访问URL本身,忽略结果并仅查看状态(200或403-Forbidden)。它在性能方面并不是最好的,但至少在功能上是正确的。但对于写入方法,我认为无法解决。希望有一个理智的解决方案来解决这个问题。

P.S。感谢@Bogdan的解决方案。这是我需要的方法的全文:

@Autowired
WebInvocationPrivilegeEvaluator evaluator;

@RequestMapping("/check")
public String check(String url, Authentication authentication) {
    return Boolean.toString(evaluator.isAllowed(url, authentication));
}

1 个答案:

答案 0 :(得分:4)

对于您发布的UtilController,您可以使用类似WebInvocationPrivilegeEvaluator的内容,也可以查看authorize tag的工作原理。

此外,根据您正在做的事情,这样的事情也可以起作用:

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

然后,您可以检查调用新方法的状态代码。

相关问题