JAVAGeek
JAVAGeek

Reputation: 2794

Restrict a user from accessing folder in Java EE app

How can I hide files on my web server? I have a directory 'files' in which I am storing some pdf files. I don't want to let the user access files by a URL like this:

www.example.com/files/1.pdf

Instead of this I want to map each file with an id in a DB and let the user access it like this:

 www.example.com/fileId=5569a

The user should not be able to access the files directory.

How can I do this?

Upvotes: 3

Views: 2556

Answers (1)

MaVRoSCy
MaVRoSCy

Reputation: 17859

that is a pretty forward answer

First of all you should deny access to the directory using the deployment descriptor (web.xml)

<security-constraint>
   <display-name>excluded</display-name>
   <web-resource-collection>
      <web-resource-name>No Access</web-resource-name>
      <url-pattern>/files/*</url-pattern>
   </web-resource-collection>
   <web-resource-collection>
      <web-resource-name>No Access</web-resource-name>
      <url-pattern>/files/*</url-pattern>
      <http-method>DELETE</http-method>
      <http-method>PUT</http-method>
      <http-method>HEAD</http-method>
      <http-method>OPTIONS</http-method>
      <http-method>TRACE</http-method>
      <http-method>GET</http-method>
      <http-method>POST</http-method>
   </web-resource-collection>
   <auth-constraint />
   <user-data-constraint>
      <transport-guarantee>NONE</transport-guarantee>
   </user-data-constraint>
</security-constraint>

Now that your files are safe you have to implement a Servlet with url-mapping '/' that will check to find the 'fileId' parameter in the request. If it finds it, the servlet will offer the file download to the user, else it will redirect the user to the homepage.

For implementing a servlet please see post Call a servlet on click of hyperlink

For implementing the file download please see my post Is there a common way to download all types of files in jsp?

Upvotes: 4

Related Questions