Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically setup a <security-constraint> in Servlets 3.x?

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>

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

UPDATE

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

like image 216
ams Avatar asked Oct 10 '13 13:10

ams


People also ask

How do I add a security constraint in web XML?

Specifically, you use the @HttpConstraint and, optionally, the @HttpMethodConstraint annotations within the @ServletSecurity annotation to specify a security constraint. If your web application does not use a servlet, however, you must specify a security-constraint element in the deployment descriptor file.

What is a security constraint?

Security constraints are a declarative way to define the protection of web content. A security constraint is used to define access privileges to a collection of resources using their URL mapping. Security constraints are defined in a deployment descriptor.

What is Servlet security?

It basically defines an HTTP authentication factory for the BASIC mechanism that relies on the servlet-security-quickstart-sd security domain to authenticate and authorize access to web applications. The following application-security-domain was added to the undertow subsystem.


1 Answers

I believe you are looking for the @ServletSecurity annotation

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

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);
like image 145
Sotirios Delimanolis Avatar answered Oct 11 '22 13:10

Sotirios Delimanolis