如何以编程方式设置< security-constraint>在Servlets 3.x? [英] How to programmatically setup a <security-constraint> in Servlets 3.x?

查看:839
本文介绍了如何以编程方式设置< security-constraint>在Servlets 3.x?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我当前的Web应用程序中,我试图摆脱web.xml,但我无法正确设置安全约束,强制所有对应用程序的请求都使用HTTPS。

In my current web application I am trying to get rid of web.xml and I have not been able to properly setup the security constraint that forces all requests to the application to use HTTPS.

<security-constraint>
  <web-resource-collection>
     <web-resource-name>all</web-resource-name>
     <url-pattern>/*</url-pattern>
  </web-resource-collection>
  <user-data-constraint>
     <transport-guarantee>CONFIDENTIAL</transport-guarantee>
  </user-data-constraint>
</security-constraint>

如何在servlet 3.x配置代码中打开上面的web.xml配置代码段同样的事情?

How can I turn the above web.xml configuration snippet in servlet 3.x configuration code that does the same thing?

UPDATE

我希望约束适用于每个servlet应用程序中的过滤器和静态资源,到目前为止我在网上看到的示例显示将安全约束附加到servlet,但我希望将安全约束附加到Web应用程序。在上面的xml片段中,您看到它没有引用任何特定的servlet

I want the constraint to apply to every servlet, filter, and static resource in application, the examples I have seen online so far show to attach a security constraint to a servlet, but I want the security constraint attached to the web app. In the xml snippet above you see that it does not reference any specific servlet

推荐答案

我相信您正在寻找 @ServletSecurity 注释

@WebServlet(urlPatterns = "/*")
@ServletSecurity(value = @HttpConstraint(transportGuarantee = TransportGuarantee.CONFIDENTIAL))
public class SomeServlet extends HttpServlet { ... } 

或者 ServletRegistration ServletContainerInitializer 中(或者您可以访问<的任何地方) code> ServletContext )

Or with ServletRegistration in a ServletContainerInitializer (or anywhere you have access to a ServletContext)

ServletRegistration.Dynamic dynamic = context.addServlet("someServlet", SomeServlet.class);
dynamic.addMapping("/*");
HttpConstraintElement httpConstraintElement = new HttpConstraintElement(TransportGuarantee.CONFIDENTIAL);
ServletSecurityElement servletSecurityElement = new ServletSecurityElement(httpConstraintElement);
dynamic.setServletSecurity(servletSecurityElement);

这篇关于如何以编程方式设置&lt; security-constraint&gt;在Servlets 3.x?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆