Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 835
JAVAGeek Avatar asked Jan 01 '26 19:01

JAVAGeek


1 Answers

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?

like image 119
MaVRoSCy Avatar answered Jan 03 '26 08:01

MaVRoSCy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!