Servlet 安全性动态注释
当您使用程序化 API 来添加或创建 Servlet 时,可以分别通过 setRunAsRole()、declareRoles() 和 setServletSecurity() 方法来动态更新安全性注释 RunAs、declareRoles 和 ServletSecurity。
注: 支持动态更新 Servlet 安全性注释 RunAs、declareRoles 和 ServletSecurity,这是此发行版的 WebSphere® Application Server 中的新功能。
当应用程序启动时,Web 容器将检查所有具有 RunAs、declareRoles 和 ServletSecurity 注释的 Servlet,并对 ServletRegistration 注释的 setServletSecurity() 方法设置这些注释。Web 容器将通知安全性组件检查所有具有 URL 模式和安全性约束的 ServletRegistration 注释。然后,安全性组件将确定部署描述符中是否定义了 URL 模式。如果在部署描述符中已定义精确匹配,那么会使用部署描述符的 URL 模式中的安全性约束和 RunAs 角色,而不使用动态数据。

在安全性动态注释中,如果您具有 ServletSecurity 注释的精确 URL 模式匹配项,那么将优先使用该安全性动态注释中的 URL 模式的安全性约束。此外,如果您多次使用同一 URL 模式调用 setServletSecurity() 方法,那么最后一次调用将具有优先权。
- ServletRegistration.Dynamic.setRunAsRole(String roleName) 将设置此 Servlet 注册的 RunAs 角色的名称。
- ServletContext.declareRoles(String roleNames) 将声明为 isUserInRole() 方法测试的角色名称。
- ServletRegistration.Dynmaic.setServletSecurity(ServletSecurityElement constraint) 将设置用于此 Servlet 注册的 ServletSecurityElement。
注: 当 Web 认证系统属性 com.ibm.wsspi.security.web.webAuthReq 设置为 persisting 时,如果提供了有效的用户名和密码,那么您可以登录到不受保护的 URL。
可以使用以下两个示例并通过使用 setServletSecurity() 方法来设置动态 Servlet 的安全性约束和 RunAs 角色。
在此示例中,所有 HTTP 元素都需要在“职员”角色中具有成员资格(PUT 方法除外)。对于 PUT 方法,<auth-constraint> 元素需要在“管理员”角色中具有成员资格,并且 TransportGuarantee 是机密的。
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 方法。对于 CUSTOM 方法,<auth-constraint> 元素需要在“管理员”角色中具有成员资格。对于 GET 方法,<auth-constraint> 元素需要在“职员”角色中具有成员资格,并且 TransportGuarantee 是机密的。
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);