2

我使用的是自定義訪問檢查與@PreAuthorize:是否可以在自定義PreAuthorize方法中獲取RequestMethod-verb?

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

我想擺脫字符串「GET」和「POST」在@PreAuthorize註釋。是否有可能在@RequestMapping中使用RequestMethod作爲hasAccessToMethod的變量輸入?

回答

2

我記不清SpEL表達式來從註釋中獲取數據,但是您可以使用SpEL從#字符中獲取方法參數的值。注入HttpServletRequest,它有一個包含你想要的getMethod方法。

@PreAuthorize("@customAccessChecker.hasAccessToMethod('USERS', #request.method)") 
@RequestMapping(method = RequestMethod.POST) 
User addUser(HttpServletRequest request) { 
    // ... 
} 
+0

這是一個理智的答案。由於註釋值需要一個常量Spring,因此不能將它與某些枚舉值連接起來。 – Andrew

+0

太棒了!它工作完美。 – maxo

+0

從請求我也可以使用#request.servletPath獲取資源名稱,而不是使用硬編碼的'USERS'字符串。 – maxo

相關問題