CIS 330: Applied Database Systems Lecture 11: HTTP Header Data - - PowerPoint PPT Presentation

cis 330 applied database systems
SMART_READER_LITE
LIVE PREVIEW

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


slide-1
SLIDE 1

CIS 330: Applied Database Systems

Lecture 11: HTTP Header Data Authentication Alan Demers ademers@cs.cornell.edu

slide-2
SLIDE 2

Road Map

§ Recap and Overview § Reading HTTP Request Headers § Reading Standard CGI Variables § Generating the Server Response

slide-3
SLIDE 3

Recap and Overview

slide-4
SLIDE 4

Overview

§ In this lecture we continue with the interaction between web browsers and servlets.

Web Browser Web Server Request Response

slide-5
SLIDE 5

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.

slide-6
SLIDE 6

Reading HTTP Request Headers

slide-7
SLIDE 7

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

slide-8
SLIDE 8

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();
slide-9
SLIDE 9

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

slide-10
SLIDE 10

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()

slide-11
SLIDE 11

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….

slide-12
SLIDE 12

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); } }

slide-13
SLIDE 13

Reading Standard CGI Variables

slide-14
SLIDE 14

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.

slide-15
SLIDE 15

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”)
slide-16
SLIDE 16

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()
slide-17
SLIDE 17

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()
slide-18
SLIDE 18

Servlet Equivalents for CGI Variables

§ SERVER_PROTOCOL

  • request.getProtocol()

§ SERVER_SOFTWARE

  • getServletContext().getServerInfo()
slide-19
SLIDE 19

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….

slide-20
SLIDE 20

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>");

} }

slide-21
SLIDE 21

Generating the Server Response

slide-22
SLIDE 22

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…

slide-23
SLIDE 23

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.
slide-24
SLIDE 24

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.

slide-25
SLIDE 25

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.

slide-26
SLIDE 26

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”);

slide-27
SLIDE 27

Case Study 1: Search Engines

slide-28
SLIDE 28

Multiple Search Engines

§ Our first case study enables users to submit a search query to one of four search engines.

  • Google
  • InfoSeek
  • Lycos
  • HotBot

§ The code exploits the HTTP Response Header to redirect the user to the correct search engine.

slide-29
SLIDE 29

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…”

slide-30
SLIDE 30

The Code

§ We are only going to examine the code superficially. § We will focus on the HTTP Return Status Code.

slide-31
SLIDE 31

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.

slide-32
SLIDE 32

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

slide-33
SLIDE 33

Case Study 2: Basic Web Security

slide-34
SLIDE 34

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.

slide-35
SLIDE 35

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 ...

slide-36
SLIDE 36

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

slide-37
SLIDE 37

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

slide-38
SLIDE 38

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).
slide-39
SLIDE 39

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==

slide-40
SLIDE 40

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.

slide-41
SLIDE 41

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
slide-42
SLIDE 42

Base 64 Encoding

§ Sun provides a class called: sun.misc.BASE64Decoder. § The decodeBuffer() method can decode the Base 64 String sent from the user:

String userInfo = “bWFydHk6bWFydHlwdw==” BASE64Decoder decoder = new BASE64Decoder(); String nameAndPassword = new String(decoder.decodeBuffer(userInfo)); § This code sets nameAndPassword to “marty:martypd”

slide-43
SLIDE 43

java.util.Properties

§ A utility class for reading in property files. § For example, suppose you have the following password.properties file: #Passwords #Sat Aug 26 11:15:42 EDT 2000 nathan=nathanpw marty=martypw lindsay=lindsaypw bj=bjpw

slide-44
SLIDE 44

java.util.Properties

§ You can easily and automatically load the password file and parse its contents:

passwordFile = "passwords.properties"; passwords = new Properties(); passwords.load(new FileInputStream(passwordFile));

§ Then, you can extract the password for a specific user name:

String password = properties.getProperty ("marty“);

slide-45
SLIDE 45

ProtectedPage.java

§ Here’s how the Servlet Works:

1) Initialization: Read in a Password file of valid user names and passwords. 2) Check for the HTTP Authorization Header. 3) Decode the Authorization Header using Base 64 to obtain user name and password. 4) Check the User Name and Password against the valid names list.

§ If valid, show protected page. § Otherwise, issue an authentication challenge.