Restricting access to WEB resources __web

Source: Internet
Author: User
Tags java web stringbuffer

One of the old questions that developers encounter is how to make resources not fully exposed to the public, but only the right people and programs have full access to the resources they need. There are at least three good ways to solve this problem.

As a Java Web Developer, you may already be familiar with the directory structure of your Web application (see Figure 1). The servlet class is placed under the Web-inf/classes directory, under Web-inf/lib is a Java archive file, such as the static resources of HTML and picture files directly in the application directory (or in any subdirectories under the application directory). For example, all picture files are placed in the picture catalog (see figure 1). JSP pages are also placed in the application directory.

Figure 1. a servlet/jsp
directory structure of the application
Fortunately, the resources placed in the Web-inf directory are safe. The user can not simply enter a URL in the browser's location or address to invoke it.

That's why many programmers put their resource files (if they were put together with the application) in the Web-inf directory. Any resource other than Web-inf can be viewed by entering a URL. HTML files and JSP files are generally invoked, so they are usually stored outside the web-inf.

However, you may want to restrict access to files outside of the Web-inf directory. There are three ways you can: by using the Referer HTTP request header ("Referer", not "referrer"), by checking a property in the user's session object, or by putting those resources in the Web-inf, and refer to them at the appropriate time. The following are guidelines for using these three methods.

Using the Referer HTTP Request Header
The Referer HTTP request header specifies a URI (uniform Resource Identifier) that contains the address of the page that is linked to the requested resource. For example, the following is a request for a JSP page called mypage1.jsp, which comes from a file called login.jsp:

http://domainName/appName/Login.jsp

If you enter a URL directly in the address or location of a Web browser to invoke mypage1.jsp, there is no referer header.

The following example uses a JSP page called displayrequestheaders.jsp:

<%@ page import= "java.util.Enumeration"%>
<% Enumeration Headers
  = Request.getheadernames ();
  while (Headers.hasmoreelements ()) {
    string header = (String) 
headers.nextelement ();
    Out.println (header + ":" + 
Request.getheader (header) + "<br>");
  }
%>

If you directly enter the URL into the browser address or location to call this page, the result is as follows:

accept:*/*
accept-language:en-us
accept-encoding:gzip, deflate
user-agent:mozilla/4.0 (compatible; MSIE 6.0; 
Windows NT 5.0. NET CLR 1.0.3705)
host:localhost:8080?connection:keep-alive
cookie:jsessionid= 65d28447dfe4f58d1d806eaa933e9dd7

However, if you request displayrequestheaders.jsp by clicking on a link in another page (such as login.jsp), you can see the following results:

Accept:image/gif, Image/x-xbitmap, Image/jpeg, 
image/pjpeg, application/vnd.ms-excel, 
Application/msword , Application/vnd.ms-powerpoint, 
*/*
referer:http://localhost:8080/myjspapp/login.jsp
Accept-language:en-us accept-encoding:gzip, deflate user-agent:mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0. NET CLR 1.0.3705) host:localhost:8080 connection:keep-alive cookie:jsessionid= 65d28447dfe4f58d1d806eaa933e9dd7

Note that the main difference between the two is that the Referer header appears in the second result. Therefore, if your application stipulates that you cannot see this resource when you directly import the URL into the browser's location or address to invoke a resource (in this case, is mypage1.jsp), then you can add this code to the top of mypage1.jsp:

if (Request.getheader ("Referer") ==null)
    response.sendredirect (Somewhereelse);
 
Where Somewhereelse is the URL of the page you want the user to enter.

Or, if you want to make sure that the resource comes from a specific URL, you can add the following code after the preceding code:

if (Request.getheader ("Referer") ==null)
    response.sendredirect (somewhereelse);
  if (Request.getheader ("Referer")!=aurl)
    response.sendredirect (Somewhereelse);

However, you need to be aware that using the Referer header is only suitable for simple control flow management. Because it relies on the request headers from the user, it is not 100% secure. Smart users who know the socket programming can often be sure that there is a referer header that contains expectations.

Check the properties of a Session object
Another way to restrict access to a particular page is by checking a specific property that appears in the user's session object. For example, if you want the abc.jsp page to be visible only to users who have logged in, you can set a property called Loggedin in the user session object after the user successfully logs on. Then at the top of the abc.jsp page, you can see if the Loggedin attribute appears in the user's session object:

<%
  if (Session.getattribute ("LoggedIn") ==null) {
%> <jsp:forward page=
    ' login.jsp
'/> <%
  }
  else {
%> 
display the page content here.

The disadvantage of this approach is that you need extra code on every page, and there are other maintenance tasks. More importantly, restricted pages require session management, which is what you might want to avoid in some applications.

Storing resources under the Web-inf directory
When you don't want users to call your JSP page, the third way--putting resources under Web-inf--can be useful. Applications that implement Model 2 architecture and Struts applications use JSP pages as View in Model-view-controller. These JSP pages are not intended to be invoked directly by the user from the browser. Instead, they are invoked from within the controller servlet. For these applications, putting JSP pages outside the Web-inf directory--As many programmers do--requires you to add additional code to restrict direct access to those resources.

On the other hand, putting them in web-inf guarantees that they can only be accessed from a servlet in that application. But if you decide to put JSP pages in the Web-inf, you need to know how to refer to those pages. Luckily, it's not difficult. The practice is as follows.

By using a RequestDispatcher object, a servlet can contain (include) or forward (forward) a JSP page. The following example forward and include a JSP page called included.jsp:

  RequestDispatcher rd = 
    request.getrequestdispatcher ("/web-
    inf/included.jsp");
  Rd.forward (request, response);

But sometimes, you need to display an HTML file instead of a JSP page. In some web containers (containers), the request dispatchers in the preceding code cannot be used for static resources (it can be used if the static resource is not under Web-inf). For these resources, you can use the getResourceAsStream method of the Javax.servlet.ServletContext interface. The method is defined as follows:

Public Java.io.InputStream 
getResourceAsStream (java.lang.String path)

To use this method, you need to send a path to the static resources you want to include. This method returns a InputStream. You can then use the InputStream Read method to get the contents of the static resource.

For example, the following JSP page contains a function called Getresourcecontent, which you can use as a string to return the contents of a static resource:

<%@ page import= "Java.io.InputStream"%>
<%!
  Public String getresourcecontent (InputStream in) {
    if (in==null) return
      null;

    StringBuffer sb = new StringBuffer (2048);
    try {
      int i = In.read ();
      while (I!=-1) {
        sb.append ((char) i);
        i = In.read ();
      }
      In.close ();
    }
    catch (Exception e) {
    } return
    sb.tostring ();
  }
%>

Note that in the JSP page, the object implied by the application represents the ServletContext object.

This JSP page shows how to include the contents of the header.html file located in the Web-inf directory. If you put the header.html file here, it cannot be invoked directly from the browser.

By using some buffering strategies, you can optimize the Getresourcecontent method in the JSP page. Here, I just explained how to get the contents of a static resource placed in the Web-inf directory.

You can use the Getresourcecontent method from within a servlet or from a JSP page. From a JSP page, you can use the indicator include, as shown in the following code:

<%@ include file= "/web-inf/header.html"%>

Now you know: You have three different ways to protect your resources and how to implement them.

Tip: For more information on securing your application, see my article on security configuration.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.