能否在自定义的PreAuthorize方法中获取请求的RequestMethod动词?

4
我正在使用带有@PreAuthorize的自定义访问检查器:
@RestController
@RequestMapping("/users")
public class Users {

    @PreAuthorize("@customAccessChecker.hasAccessToMethod('USERS', 'GET')")
    @RequestMapping(method = RequestMethod.GET)
    User getUsers() {
        ...
    }

    @PreAuthorize("@customAccessChecker.hasAccessToMethod('USERS', 'POST')")
    @RequestMapping(method = RequestMethod.POST)
    User addUser() {
        ...
    }
}

我希望在@PreAuthorize注解中去掉字符串“GET”和“POST”。是否有可能以变量输入的方式获取@ RequestMapping中使用的RequestMethod,以便在hasAccessToMethod中使用?

1个回答

6
我记不住从注解中获取数据的SpEL表达式,但是你可以使用SpEL通过#字符来获取你方法参数的值。注入HttpServletRequest,它有一个getMethod方法,包含了你想要的内容。
@PreAuthorize("@customAccessChecker.hasAccessToMethod('USERS', #request.method)")
@RequestMapping(method = RequestMethod.POST)
User addUser(HttpServletRequest request) {
    // ...
}

这是一个明智的答案。由于注解值需要一个常量Spring,您无法将其与某个枚举值连接起来。 - Andrew Tobilko
从请求中,我也可以使用#request.servletPath获取资源名称,而不是使用硬编码的“USERS”字符串。 - maxo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接