我見過很多問題,要求如何處理安全方案,都有解決方法註釋(即@PreAuthorize("hasRole('ROLE_USER')")
)或使用切點。什麼是正確的方法來拒絕訪問特定資源在春天MVC +安全
但是,如果用戶訪問資源直到資源從數據存儲中讀取,那麼資源未知?讓我們考慮可以訪問一組客戶的用戶,其他客戶端可以在/customers/{id}
找到。用戶只有在被授予閱讀帳戶權限的情況下才被允許訪問,同樣他們也必須有權訪問相同的端點以創建POST
。
一種方法是:
@RequestMapping(value = "/customers/{id}", method = RequestMethod.GET)
public ModelAndView customerPage(String id, HttpServletRequest req, Principal principal) {
if (!req.isUserInRole("ROLE_ADMIN") && !cs.accessGranted(id, principal.getName())) {
throw new AccessDeniedException("You do not have access to view this custoemr.");
}
Customer cust = cs.getCustomer(id);
if (cust == null) {
throw new ResourceNotFoundException("Customer does not exist!");
}
ModelAndView mov = new ModelAndView("customers/info");
mov.addObject("customer", cust);
return mov;
}
我想知道如果這是正確的做法,但。
UPDATE:致電accessGranted
的意思是讓id
作爲我錯過的論點。
這是一個很好的方法,我實際上更喜歡SpEL來引用服務的實例成員,這樣我就不需要命名我的服務bean,儘管我認爲你的解決方案是最靈活的。 –
好主意。你如何獲得參考成員?使用'#root'變量? –
我認爲它實際上是'#this',但我相信你不能訪問成員,但可以訪問訪問器。我沒有嘗試過,但是'@PreAuthorize(「hasRole('ROLE_ADMIN')or!#this.accessGranted(#id,#principal.getName())」)''。我認爲'#principal'在spring安全表達式中可以自動使用。我從來沒有真正使用SpEL,即使我把它全部打開,我也無法使註釋工作,他們似乎被忽略了。 –