2012-07-04 90 views
2

我在Vaadin應用程序中使用Spring和Spring-Security。訪問SecurityContextHolderAwareRequestWrapper實例?

我想檢查用戶是否具有使用SecurityContextHolderAwareRequestWrapper.isUserInRole(...)的某個角色,但無法弄清楚如何獲得對包裝的引用(我嘗試使用@Autowired注入此註釋,注意:我沒有手動將其實例配置爲我相信DelegatingFilterProxy已經在幕後做這個了)。

This堆棧溢出問題爲我提供瞭解決方案,但我無法發現如何正確訪問或實例化封裝。

我的另一種選擇是直接訪問SecurityContext並根據鏈接的SO問題中的其他建議迭代GrantedAuthorities。

我應該如何訪問/實例化包裝?

回答

5

它應該開箱即用,至少在Spring Security 3.1中(安全鏈中的每個HttpServletRequest應該是SecurityContextHolderAwareRequestWrapper的實例)。

servlet-api-provision attribute of <http> element增加堆疊:

HttpServletRequest提供的版本的安全方法,如 的isUserInRole()和getPrincipal(),它是通過將 SecurityContextHolderAwareRequestFilter豆到堆棧實現。默認爲 爲真。

過濾SecurityContextHolderAwareRequestFilter很簡單,只有包裝HttpServletRequestSecurityContextHolderAwareRequestWrapper:(小心bug #SEC-1943 - 過濾器因錯誤的名稱分配給別名SERVLET_API_SUPPORT_FILTER

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) 
     throws IOException, ServletException { 
    chain.doFilter(new SecurityContextHolderAwareRequestWrapper(
      (HttpServletRequest) req, rolePrefix), res); 
} 

+0

嗯我使用的是3.0 .2並且無法升級。 – Syntax

+0

剛剛檢查過3.0.X文檔和代碼 - [應該是相同的](http://static.springsource.org/spring-security/site/docs/3.0.x/reference/springsecurity-single.html#nsa-servlet -API撥備)。你能否明確地將''添加到你的安全bean配置中? – Xaerxess

+0

酷,所以我的應用程序是一個HttpServletRequestListener,我收到onRequestStart上的HttpServletRequest的引用;通過它我可以檢查/轉換到SecurityContextHolderAwareRequestWrapper並進行適當的調用。謝謝你的幫助! – Syntax