Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

programmatically retrieve security constraints from web.xml

Is there any possiblity to obtain the list of constraints from web.xml ?

 <security-constraint>
    <web-resource-collection>
        <web-resource-name>admin</web-resource-name>
        <url-pattern>/admin/*</url-pattern>
    </web-resource-collection>
    <auth-constraint>
        <role-name>admin</role-name>
    </auth-constraint>
 </security-constraint>

Even better is there a programmatic way to add new constraints ?

Thanks, Victor

like image 265
victor Avatar asked Aug 10 '26 07:08

victor


1 Answers

If you have a ServletContainerInitializer, in its onStartup() method, you would basically do what your container does when it parses your web.xml. For example:

@Override
public void onStartup(Set<Class<?>> classes, ServletContext ctx) throws ServletException {
    ServletRegistration.Dynamic servlet = ctx.addServlet("myServlet", "com.package.myServlet"); // loop through classes set to find all your servlets
    HttpConstraintElement constraint = new HttpConstraintElement(); // many constructors with options
    ServletSecurityElement securityElement = new ServletSecurityElement(constraint); // many different constructors
    servlet.setServletSecurity(securityElement);
}

There are a lot of options in the constructors I've commented for all sorts of configurations, even through the servlet 3.0 security annotations. I'll let you discover them all.

As for adding new constraints after initialization, the javadoc for setServletSecurity() says:

* @throws IllegalStateException if the {@link ServletContext} from
* which this <code>ServletRegistration</code> was obtained has
* already been initialized

I couldn't find anything for obtaining a list of constraints through ServletContext interface, but you can always parse the web.xml yourself.

like image 69
Sotirios Delimanolis Avatar answered Aug 12 '26 03:08

Sotirios Delimanolis