views:

192

answers:

2

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?

+2  A: 

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>
Nathan
That works great for me. I've written my own filter.
Mnementh
+3  A: 

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>
svachon
That would indeed be the prefered way to do it using realms.
Nathan
How I can define the usernames/passwords this way?
Mnementh
It depends of the app server you are using. For Tomcat, google "jdbc realm configuration". For websphere, the prefered way would be ldap.
svachon
As I want to only deploy a war with my application and no further configuration needed, I prefer the Filter-solution, sorry. But your answer is also good, upvote.
Mnementh