In a Java-webapp (war), how can I use HTTP-auth for static content?
-
05-07-2019 - |
Question
I have a Java-webapp. The webapp is packaged as a war-file. These war-file allow static content, that is directly delivered via HTTP. For servlets in this war I can make a HTTP-authentication (implement it with the servlet itself). But I also want HTTP-auth for the static content. How can I realize this?
Solution
Create a class that implements javax.servlet.Filter. See The Essentials of Filters
The main method is doFilter that is passed the ServletRequest, ServletResponse and FilterChain objects. That's where you enforce authentication.
Then declare your filter in web.xml and a filter mapping as following (maps to every request)
<filter>
<filter-name>Authentication Filter</filter-name>
<filter-class>
com.nfsdsystems.security.filters.AuthenticationFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>Authentication Filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
OTHER TIPS
Put your static html files in a direcotry and define your security constraints in your web.xml. Map the constraints to the appropriate role.
<security-constraint>
<display-name>securedResources</display-name>
<web-resource-collection>
<web-resource-name>securedRes</web-resource-name>
<url-pattern>/secured/*</url-pattern>
<http-method>GET</http-method>
<http-method>PUT</http-method>
<http-method>HEAD</http-method>
<http-method>TRACE</http-method>
<http-method>POST</http-method>
<http-method>DELETE</http-method>
<http-method>OPTIONS</http-method>
</web-resource-collection>
<auth-constraint>
<description>
authenticatedUser_securedRes</description>
<role-name>authenticatedUsed</role-name>
</auth-constraint>
</security-constraint>