CIS 330: Applied Database Systems Lecture 11: HTTP Header Data - - PowerPoint PPT Presentation
CIS 330: Applied Database Systems Lecture 11: HTTP Header Data - - PowerPoint PPT Presentation
CIS 330: Applied Database Systems Lecture 11: HTTP Header Data Authentication Alan Demers ademers@cs.cornell.edu Road Map Recap and Overview Reading HTTP Request Headers Reading Standard CGI Variables Generating the Server
Road Map
§ Recap and Overview § Reading HTTP Request Headers § Reading Standard CGI Variables § Generating the Server Response
Recap and Overview
Overview
§ In this lecture we continue with the interaction between web browsers and servlets.
Web Browser Web Server Request Response
Client Request Data
§ When a user submits a browser request to a web server, it sends two categories of data:
- Form Data: Data that the user explicitly typed into an
HTML form.
§ For example: registration information.
- HTTP Request Header Data: Data that is
automatically appended to the HTTP Request from the client.
§ For example: cookies, browser type, etc,
§ We already examined Form Data; here we examine HTTP Data.
Reading HTTP Request Headers
Sample HTTP Request
§ As a refresher, let’s take a look at a sample HTTP Request to Yahoo.com
GET / HTTP/1.1 Accept: */* Accept-Language: en-us Accept-Encoding: gzip, deflate User-Agent: Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt) Host: www.yahoo.com Connection: Keep-Alive Cookie: B=2td79o0sjlf5r&b=2
Accessing HTTP Headers
§ To access any of these Headers, the use the HTTPServletRequest getHeader() method. § For example:
- String connection = req.getHeader(“Connection”);
§ To retrieve a list of all the Header Names, use the getHeaderNames() method.
- getHeaderNames() returns an Enumeration object.
§ For example:
- Enumeration enum = req.getHeaderNames();
Additional HTTP Information
§ getMethod()
- Indicates the request method, e.g. GET or POST.
§ getRequestURI()
- Returns the part of the URL that comes after the host
and port. For example, for the URL: http:// randomhost.com/servlet/search, the request URI would be /servlet/search.
§ getProtocol()
- Returns the protocol version, e.g. HTTP/1.0 or HTTP/
1.1
Example 1
§ Our first example echoes all of the HTTP Request Information. § First, it outputs:
- Method
- RequestURI
- Protocol Version
§ Then, it calls getHeaderNames() to retrieve a list
- f all HTTP Header Names.
§ For each header name, it then calls getHeader()
package coreservlets; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; public class ShowRequestHeaders extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Servlet Example: Showing Request Headers";
- ut.println(ServletUtilities.headWithTitle(title) +
"<BODY BGCOLOR=\"#FDF5E6\">\n" + "<H1 ALIGN=CENTER>" + title + "</H1>\n" + "<B>Request Method: </B>" + request.getMethod() + "<BR>\n" + "<B>Request URI: </B>" + request.getRequestURI() + "<BR>\n" + "<B>Request Protocol: </B>" + request.getProtocol() + "<BR><BR>\n" + "<TABLE BORDER=1 ALIGN=CENTER>\n" + "<TR BGCOLOR=\"#FFAD00\">\n" + "<TH>Header Name<TH>Header Value");
Continued….
Enumeration headerNames = request.getHeaderNames(); while(headerNames.hasMoreElements()) { String headerName = (String)headerNames.nextElement();
- ut.println("<TR><TD>" + headerName);
- ut.println(" <TD>" + request.getHeader(headerName));
}
- ut.println("</TABLE>\n</BODY></HTML>");
} /** Let the same servlet handle both GET and POST. */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
Reading Standard CGI Variables
CGI Variables
§ In addition to HTTP Request headers, you can also determine additional information about both the client and the server:
- IP Address of Client
- Host Name of Client
- Server Name
- Server Port
- Server Protocol
- Server Software
§ Additional information is also available.
Servlet Equivalents for CGI Variables
§ AUTH_TYPE
- request.getAuthType()
§ CONTENT_LENGTH
- request.getContentLength()
§ CONTENT_TYPE
- request.getContentType()
§ DOCUMENT_ROOT
- getServletContext().getRealPath(”/”)
§ HTTP_XXX_YYY
- request.getHeader(”XXX_YYY”)
Servlet Equivalents for CGI Variables
§ PATH_INFO
- request.getPathInfo()
§ PATH_TRANSLATED
- request.getPathTranslated()
§ QUERY_STRING
- request.getQueryString()
§ REMOTE_ADDR
- request.getRemoteAddr()
§ REMOTE_HOST
- request.getRemoteHost()
Servlet Equivalents for CGI Variables
§ REMOTE_USER
- request.getRemoteUser()
§ REQUEST_METHOD
- request.getMethod()
§ SCRIPT_NAME
- request.getServletPath()
§ SERVER_NAME
- request.getServerName()
§ SERVER_PORT
- request.getServerPort()
Servlet Equivalents for CGI Variables
§ SERVER_PROTOCOL
- request.getProtocol()
§ SERVER_SOFTWARE
- getServletContext().getServerInfo()
Example 2
§ Display the most important CGI Variables ...
package coreservlets; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; public class ShowCGIVariables extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String[][] variables = { { "REMOTE_ADDR", request.getRemoteAddr() }, { "REMOTE_HOST", request.getRemoteHost() }, { "SERVER_NAME", request.getServerName() }, { "SERVER_PORT", String.valueOf(request.getServerPort()) }, { "SERVER_PROTOCOL", request.getProtocol() }, { "SERVER_SOFTWARE", getServletContext().getServerInfo() } };
Continued….
String title = "Servlet Example: Showing CGI Variables";
- ut.println(ServletUtilities.headWithTitle(title) +
"<BODY BGCOLOR=\"#FDF5E6\">\n" + "<H1 ALIGN=\"CENTER\">" + title + "</H1>\n" + "<TABLE BORDER=1 ALIGN=\"CENTER\">\n" + "<TR BGCOLOR=\"#FFAD00\">\n" + "<TH>CGI Variable Name<TH>Value"); for(int i=0; i<variables.length; i++) { String varName = variables[i][0]; String varValue = variables[i][1]; if (varValue == null) varValue = "<I>Not specified</I>";
- ut.println("<TR><TD>" + varName + "<TD>" + varValue);
}
- ut.println("</TABLE></BODY></HTML>");
} }
Generating the Server Response
Sample HTTP Response
§ As a refresher, here’s a sample HTTP response:
HTTP/1.1 200 OK Date: Mon, 06 Dec 1999 20:54:26 GMT Server: Apache/1.3.6 (Unix) Last-Modified: Fri, 04 Oct 1996 14:06:11 GMT Content-length: 327 Connection: close Content-type: text/html <title>Sample Homepage</title> <img src="/images/oreilly_mast.gif"> <h1>Welcome</h2>Hi there, this is a simple web page. Granted, it may…
Generating Responses
§ Servlets can return any HTTP response they want. § Useful for lots of scenarios:
- Redirecting to another web site.
- Restricting access to approved users.
- Return images instead of HTML.
Setting the HTTP Status Code
§ By default, your Servlet will return an HTTP Status code of: 200 OK to indicate that everything went fine. § To return a different status code, use the setStatus() method of the HttpServletResponse object. § Be sure to set the status code before sending any document content to the client.
Using setStatus()
§ setStatus takes an integer value. But, it’s best to use the predefined integers in the HttpServletResponse. Here are a few: § SC_BAD_REQUEST
- Status code (400) indicating the request sent by the
client was syntactically incorrect. § SC_FORBIDDEN
- Status code (403) indicating the server understood
the request but refused to fulfill it. § SC_INTERNAL_SERVER_ERROR
- Status code (500) indicating an error inside the HTTP
server which prevented it from fulfilling the request. § SC_NOT_FOUND
- Status code (404) indicating that the requested
resource is not available.
Sending Redirects
§ You can redirect the browser to a different URL by issuing a Moved Temporarily Status Code:
- SC_MOVED_TEMPORARILY: Status code
(302) indicating that the resource has temporarily moved to another location.
§ Because this is so common, the HttpServletResponse interface also has a sendRedirect() method.
- Example:
res.sendRedirect( “http://www.yahoo.com”);
Case Study 1: Search Engines
Multiple Search Engines
§ Our first case study enables users to submit a search query to one of four search engines.
- InfoSeek
- Lycos
- HotBot
§ The code exploits the HTTP Response Header to redirect the user to the correct search engine.
Architecture
Web Browser SearchEngines Servlet “I want to search for Bill Gates on Google” “Go to Google” Google “I want to search for Bill Gates on Google” “Your results…”
The Code
§ We are only going to examine the code superficially. § We will focus on the HTTP Return Status Code.
SearchSpec.java
§ For our purposes, we only need to know about
- ne method:
- public String makeURL (String searchString, String
numResults)
- You provide this method with a search string and the
number of results, and it returns the URL and search query specific to Google, InfoSeek, HotBot, etc.
§ The SearchEngines.java code has an array of these objects: one for Google, one for InfoSeek, etc.
String searchEngine=request.getParameter("searchEngine"); SearchSpec[] commonSpecs = SearchSpec.getCommonSpecs(); for(int i=0; i<commonSpecs.length; i++) { SearchSpec searchSpec = commonSpecs[i]; if (searchSpec.getName().equals(searchEngine)) { String url = searchSpec.makeURL(searchString, numResults); response.sendRedirect(url); return; }
Get the Array of SearchSpec Objects Get the searchEngine Param Iterate through the array, looking for a match... Get the Search URL and Redirect Browser
Case Study 2: Basic Web Security
HTTP Authentication
§ The HTTP Protocol Includes a built-in authentication mechanism. § Useful for protecting web pages or servlets that require user name / password access. § First, we’ll examine BASIC authentication and the HTTP Headers involved. § Then, we’ll build a servlet that exploits this mechanism.
An Aside ...
§ HTTP Authentication includes other (more elaborate and more secure) schemes besides BASIC. § “Digest” scheme avoids sending passwords in the clear ...
§ (note https encrypts entire stream)
§ See rfc2617 for details ...
Basic Authentication
1) If a web page is protected, the Web Server will issue an authentication “challenge”:
HTTP/1.1 401 Authorization Required Date: Sun, 27 Aug 2000 17:51:25 GMT Server: Apache/1.3.12 (Unix) ApacheJServ/1.1 PHP/4.0.0 mod_ssl/2.6.6 OpenSSL/0.9.5a WWW-Authenticate: BASIC realm="privileged-few" Keep-Alive: timeout=90, max=150 Connection: Keep-Alive Transfer-Encoding: chunked Content-Type: text/html
WWW-Authenticate: BASIC realm=“realm" § When you issue a return status code of 401, “Authorization Required”, you must tell the client what type of authentication is required. § You do this in the WWW-Authenticate Header. This header has two parameters:
- BASIC: Basic authorization requiring user
name and password.
- Realm: you can create multiple “realms” of
authentication for different users, e.g. “Admin”, “User”, “Super_User”, etc.
WWW-Authenticate
Basic Authentication (continued)
1) Upon receiving an authentication challenge, the browser will prompt the user with a pop-up box requesting the user name and password. 2) Browser takes the “username:password” from the user and encodes it using the Base 64 Encoding Algorithm.
- For example: if the string is “marty:martypd”, the Base 64
string is “bWFydHk6bWFydHlwdw==”
- We will not cover the details of Base 64, but remember that
Base 64 is not encryption - it is easy to decode. Therefore, even if your page is password protected, someone can easily intercept your Base 64 string and decode it.
- You need to encrypt the traffic using SSL/TLS/HTTPS (later).
Basic Authentication (continued)
1) The browser reissues the request for the page. In the HTTP request, the browser indicates the Authorization string:
GET /servlet/coreservlets.ProtectedPage HTTP/1.1 Accept: image/gif, */* Accept-Language: en-us Accept-Encoding: gzip, deflate User-Agent: Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt) Host: www.ecerami.com Connection: Keep-Alive Authorization: Basic bWFydHk6bWFydHlwdw==
Basic Authentication (continued)
- 1. Web Server checks the user name and
password.
- If User Name/Password is correct, web
server displays the protected page.
- If the User Name/Password is incorrect,
web server issues a second authentication challenge.
Almost there…
§ Before we examine the actual servlet code, there are two pieces of Java coding we need to examine:
- sun.misc.BASE64Decoder.
- java.util.Properties