Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Tomcat Basic Auth with new WebApplicationInitializer

OK so I've previously used this technique with classic web.xml, but am having trouble getting it to work now that I'm using the WebApplicationInitializer.

My WebApplicationInitializer includes this code:

HttpConstraintElement constraint = new HttpConstraintElement(
        TransportGuarantee.NONE,
        new String[]{"sponsorUsers"});
ServletSecurityElement servletSecurity =
        new ServletSecurityElement(constraint);
dispatcher.setServletSecurity(servletSecurity);

I'm trying to require basic auth (username+password) for any http methods for any resource request within the servlet. All I get back is a 403 - no prompt for the username. My suspicion is that I need to set the auth-method to BASIC, as I would in xml:

<login-config>
    <auth-method>BASIC</auth-method>
    <realm-name>User Auth</realm-name>
</login-config>

But don't see the equivalent in the Java classes. Any help? Thanks!

like image 828
Bobby Avatar asked May 10 '26 19:05

Bobby


1 Answers

A WebApplicationInitializer is basically the Spring extension of Servlet 3.0 ServletContainerInitializer.

There are a few things you cannot do with ServletContainerInitializer, or ServletContext to be more specific, and one of them is to configure some security components, ex login-config.

Instead you can have both a ServletContainerInitializer and a web.xml using the attribute metadata-complete set to false. For example,

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    metadata-complete="false" version="3.0">

In which you then add your <login-config> element.

like image 142
Sotirios Delimanolis Avatar answered May 12 '26 09:05

Sotirios Delimanolis