Servlet 安全動態註釋

當您使用程式化 API 來新增或建立 Servlet 時,安全註釋、執行身分、declareRoles 和 ServletSecurity 可以分別透過 setRunAsRole ()、declareRoles () 和 setServletSecurity () 方法來動態更新。

附註: 在這個 WebSphere® Application Server版本中,對於動態更新執行身分、declareRoles 和 ServletSecurity Servlet 安全註釋的支援是全新的。

當應用程式啟動時, Web 儲存器會使用 RunAs、declareRoles 和 ServletSecurity 註釋來檢查所有 Servlet ,並在 ServletRegistration 註釋的 setServletSecurity () 方法上設定那些註釋。 Web 儲存器會通知安全元件檢查所有具有 URL 型樣和安全限制的 ServletRegistration 註釋。 然後安全元件會決定是否在部署描述子中定義 URL 型樣。 如果部署描述子中已定義完全相符,則會使用部署描述子 URL 型樣中的安全限制和執行身分角色,而不是動態資料。

避免麻煩: 如果使用動態安全註釋、declareRoles、setRunAs 和 rolesAllowed ,則必須透過部署描述子,或透過 Servlet 類別中的 declareRoles 和/或 RunAs 註釋,預先定義角色名稱。 在部署期間,您可以使用管理主控台,將使用者或群組對映至這個角色。

如果您在安全動態註釋中有完全符合 ServletSecurity 註釋的 URL 型樣,安全動態註釋中 URL 型樣的安全限制會成為先例。 此外,如果您使用相同的 URL 型樣多次呼叫 setServletSecurity () 方法,則最後一個方法會有先例。

  • ServletRegistration.Dynamic.setRunAsRole (String roleName) 會設定這個 Servlet 登錄的執行身分角色名稱。
  • ServletContext.declareRoles (String roleNames) 宣告針對 isUserInRole () 方法測試的角色名稱。
  • ServletRegistration.Dynmaic.setServletSecurity (ServletSecurityElement 限制項) 會設定此 Servlet 登錄的 ServletSecurityElement。
附註: 當 Web 鑑別系統內容 com.ibm.wsspi.security.web.webAuthReq 設為 persisting時,如果提供有效的使用者名稱和密碼,您可以登入不受保護的 URL。

下列兩個範例可用來利用 setServletSecurity () 方法來設定動態 Servlet 的安全限制和執行身分角色。

在此範例中,除了 PUT 方法之外,所有 HTTP 元素都需要 Employee 角色的成員資格。 For the PUT method, the <auth-constraint> element requires membership in the Manager role and TransportGuarantee is confidential.
HttpConstraintElement constraint = new HttpConstraintElement(TransportGuarantee.NONE,
new String[]{"Employee"});
List<HttpMethodConstraintElement> methodConstraints =
new ArrayList<HttpMethodConstraintElement>();
methodConstraints.add(new HttpMethodConstraintElement("PUT",
new HttpConstraintElement(TransportGuarantee.CONFIDENTIAL, new String[]{"Manager"})));
ServletSecurityElement servletSecurity =
new ServletSecurityElement(constraint, methodConstraints);
在此範例中,除了 CUSTOM 和 GET 方法之外,接受所有 HTTP 方法。 For the CUSTOM method, the <auth-constraint> element requires membership in the Manager role. For the GET method, the <auth-constraint> element requires membership in the Employee role, and TransportGuarantee is confidential.
HttpConstraintElement constraint = new HttpConstraintElement();
List<HttpMethodConstraintElement> methodConstraints = 
new ArrayList<HttpMethodConstraintElement>();
methodConstraints.add(new HttpMethodConstraintElement("CUSTOM", 
new HttpConstraintElement(TransportGuarantee.NONE, new String[]{"Manager"})));
methodConstraints.add(new HttpMethodConstraintElement("GET", 
new HttpConstraintElement(TransportGuarantee.CONFIDENTIAL, new String[]{"Employee"})));
ServletSecurityElement servletSecurity = new ServletSecurityElement(constraint, 
methodConstraints);