2013-02-06 64 views
2

鑑於我無法創建任何新角色,因爲它們是在CAS服務器中創建的,並且我沒有對它們的任何控制,是否有一種方法可以保護僅打開的PDF文件如果用戶既具有「客戶」角色又具有「專業」角色?web.xml安全約束角色組合

換句話說,考慮到以下三個用戶:

USER1只有「顧客」的角色 用戶2具有「客戶」和「專業」的角色 用戶3具有「客戶」和「專業」的角色 USER4有隻有「專業」角色

只有user2和user3應該被允許看到PDF。

基本上,我想這樣做:

<security-constraint> 
    <web-resource-collection> 
     <web-resource-name>auth</web-resource-name> 
     <url-pattern>/doc/profesionalCustomer.pdf</url-pattern> 
    </web-resource-collection> 
    <auth-constraint> 
     <role-name>professional,customer</role-name> 
    </auth-constraint> 
</security-constraint> 

這甚至可能嗎?

預先感謝

回答

4

這是不可能使用聲明安全(即經由web.xml)中。你可以只列出有訪問資源的角色,如以下:

<security-constraint> 
<web-resource-collection> 
    <web-resource-name>auth</web-resource-name> 
    <url-pattern>/doc/profesionalCustomer.pdf</url-pattern> 
</web-resource-collection> 
<auth-constraint> 
    <role-name>professional</role-name> 
    <role-name>customer</role-name> 
</auth-constraint> 

但是在這種情況下,你會獲得訪問權要麼專業或客戶角色的所有用戶這是不是你想。沒有允許您爲具有角色組合的用戶授予訪問權限的結構。

你可以採取的一種方法是以編程方式處理它:將客戶端指向一個servlet,該servlet使用HttpServletRequest#isUserInRole(String)來檢查用戶是否具有客戶和專業角色,並且它將請求轉發給默認servlet檢索pdf。此外,如果您想推遲什麼組合角色被授予訪問部署時間的權限,而不是在servlet中對其進行硬編碼,則可以通過您的web.xml的/web-app/servlet/init-param或元素正確參數化servlet。

以下是摘錄的web.xml將支持這一點:

<servlet> 
    <servlet-name>PDF Retriever</servlet-name> 
    <servlet-class>com.stackoverflow.PDFRetrieverServlet</servlet-class> 
</servlet> 
<servlet-mapping> 
    <servlet-name>PDF Retriever</servlet-name> 
    <url-pattern>/docs/pdf/*</url-pattern> 
</servlet-mapping> 
<security-constraint> 
    <web-resource-collection> 
     <web-resource-name>PDF Docs - customer and professional only</web-resource-name> 
     <url-pattern>/docs/pdf/*</url-pattern> 
    </web-resource-collection> 
    <auth-constraint> 
     <role-name>*</role-name> 
    </auth-constraint> 
</security-constraint> 
<security-constraint> 
    <web-resource-collection> 
     <web-resource-name>PDF Docs Private</web-resource-name> 
     <url-pattern>/private/pdf/*</url-pattern> 
    </web-resource-collection> 
    <auth-constraint> 
     <role-name /> 
    </auth-constraint> 
</security-constraint>` 

,這裏是編碼的servlet的doGet:

protected void doGet(HttpServletRequest request, 
    HttpServletResponse response) throws ServletException, IOException { 
    if (request.isUserInRole("customer") && request.isUserInRole("professional")) { 
     String urlSuffix = request.getPathInfo(); 
     RequestDispatcher rd = request.getRequestDispatcher("/private/pdf" 
       + urlSuffix); 
      rd.forward(request, response); 
    } else { 
      response.sendError(HttpServletResponse.SC_FORBIDDEN); 
    } 
} 
+0

謝謝你的回答。 我唯一擔心的是,如果有人知道PDF文件的完整路徑,他可以直接訪問它,而無需任何控制。 – Pierpaolo

+0

@Pierpaolo我編輯了包含web.xml和servlet代碼的答案。爲了防止每個人訪問PDF,您可以將URL放置在一個沒有角色可以訪問的保護區中(您的pdf文件實際位於/ private/pdf目錄下) - 請注意第二個空角色名稱元素安全性約束。唯一的訪問是通過PDFRetrievalServlet。 – Nenad