Implementing a Bank Account using Ajax into a shopping cart

an article added by: Sonja Lande at 06012007


In: Categories » » AJAX » Implementing a Bank Account using Ajax into a shopping cart

Implementing a bank account is similar to implementing a shopping cart. The only real difference is that you need security. For example, if maryjane logs into her account and she references the URL /account/maryjane, then you only want maryjane or an appropriate person to view the data. Anybody else should get an invalid security credentials error. The remainder of this article will focus on how to use cookies and HTTP authentication to authenticate users:

• HTTP cookies: HTTP cookies are identifiers sent in the HTTP header between the client and the server. The server is responsible for generating a cookie, and the client is responsible for sending the cookie to the server for a given URL and its descendents.

HTTP authentication: By using HTTP authentication, it is possible to authenticate users. Then, whenever the users request content for a given URL realm, the client sends the authorization information. HTTP authentication is similar to a cookie, except that users must authenticate themselves. Whether you use cookies or HTTP authentication, the clients send a token whenever they wish to access a given URL. The server will validate if the token has permission to access the URL.

Using Cookies to Authorize Access

HTTP cookies4 have a bad reputation, partially undeserved, and therefore many will argue that you should not use cookies. The problem with cookies doesn’t have to do with their theory, but rather with their implementation and ramifications. As a real-life analogy, consider entering a shopping mall where somebody gives you a token at the entrance, which you can take or refuse. If you refuse the token and enter the mall, all of the store doors suddenly close. You can wander the mall, but you can only look at the merchandise through the windows. You can still view the content and everything that the store offers, but it is behind glass. On the other hand, if you accept the token, the store doors remain open, and you can browse all the products. To be helpful, the store clerks offer recommendations on the best offers in the mall. Yet there is a dark undertone to the experience: the shopping mall is watching every step you make, and everything you look at is being tracked. Of course, the shopping mall assures you that the information will not be used for other purposes, but the question is, where do those recommendations or best offers come from? The tokens or cookies are being used to track people. I’m split regarding the use of cookies I find nothing extremely disturbing about them, nor am I enthused about them. HTTP cookies are a means to an end.

Generating the Cookie

It is possible to generate an HTTP cookie5 without using any help from a library. Because of the prevalence of cookies, most server-side libraries have classes or functions to generate cookies based on a few parameters. Using the available server-side libraries is highly recommended. Generating the cookie by using the server-side libraries is not difficult. When using ASP.NET, you would use the following source code:

   HttpCookie mycookie = new  HttpCookie("Sample", "myvalue");
   mycookie.Path = "/ajax/chap07";
 Page.Response.Cookies.Add(mycookie);

You instantiate a cookie (HttpCookie), and at aminimum, you specify the key (Sample) and value (myvalue). The combination key-value pair is sent between the client and server. The cookie property mycookie.Path specifies for which URL and its descendents the cookie is valid. Comparing this to HTTP authentication, the cookie path is equal to the HTTP authentication realm. You add the newly created cookie to the response by using the method Page.Response. Cookies.Add. When a cookie is added, the HTTP response will generate a cookie using the Set-Cookie HTTP header, as illustrated by the following HTTP server response:

   HTTP/1.0 200 OK
   Server: Mono-XSP Server/1.1.13.0 Unix
   X-Powered-By: Mono
   Date: Mon, 28 Aug 2006 17:31:14 GMT
   Content-Type: text/html; charset=utf-8
   Set-Cookie: Sample=myvalue; path=/ajax/chap05
   Content-Length: 388
   Keep-Alive: timeout=15, max=99
 Connection: Keep-Alive

The cookie Sample has a value of myvalue and is valid for the path /ajax/chap05. Because there is no expires value, the cookie is valid only for the lifetime of the browser. If the browser is closed, the cookie is deleted, thus behaving like an HTTP authentication-based user identifier.

Understanding How the Client Manages the Cookie

When the client receives the cookie, the cookie will be saved automatically if the client is a browser or the XMLHttpRequest object of the browser. In fact, the JavaScript on the client side has absolutely nothing to do with the assigned cookie, because everything occurs transparently. For example, if a browser loads a page and a cookie is assigned for the entire domain, the cookie will be sent when the XMLHttpRequest object calls a page within the domain. Storing sensitive information, such as passwords or any kind of personal information, within the cookie is not recommended. A cookie is a reference to information, not a repository for information. When users have been authenticated by using other means, a cookie should be used only as a token to identify the user.

Identifying a User with a Cookie

When the server generates a cookie, it means nothing, because a cookie is just a token. The cookie needs to be cross-referenced with a specific user. To crossreference the token, you must apply an authentication mechanism. You could use one of two authentication mechanisms. First, you could tie the cookie with HTTP authentication. Second, you could create an HTML page that associates the cookie with a user. Using HTTP authentication to associate a user with a cookie would involve protecting a file that requires an explicit authentication. When the user is authenticated by using HTTP authentication, the protected file is responsible for associating the cookie and authentication information. The user does not have to be authenticated using HTTP authentication. An HTML form could be used instead. Using the HTML form, you’re responsible for providing code that manages a user. Because of this added code, the HTTP authentication mechanism is preferred, because it is the basis of the HTTP protocol.

Using HTTP Authentication

HTTP authentication is probably one of the most underused techniques of creating a user identifier. Most Web applications tend to prefer HTTP cookies, but HTTP authentication offers some yet-to-be-discussed options that HTTP cookies do not. In the early nineties, HTTP authentication was not well known and was considered generally insecure, because the client would constantly be sending the username and password to the server whenever an authorization was performed. To get around the security issue, a more secure form of HTTP authentication was created, called HTTP digest authentication. HTTP digest authentication was not widely distributed in the early Web days. Of course, today that is not the case, as every browser, or at least most browsers, support HTTP digest authentication. HTTP authentication is both a blessing and a curse, in that users must authenticate themselves whenever they exit and restart the browser. The blessing is that authentication information is not sent automatically, and the curse is that users must authenticate themselves before starting a session at aWeb site. Some may consider requiring to be authenticated a downside, but when security is important, using HTTP authentication ensures giving the correct rights to the identified user. At a technical level, HTTP authentication is a mechanism whereby a user requests the contents of a resource, and the server issues a challenge, asking for identification. After the user enters the appropriate information, the server will authenticate the user. If the authentication works, the browser downloads the representation of the resource. A typical HTTP digest authentication conversation is described in the following steps. The process starts with the client requesting a resource:

   GET /test/ HTTP/1.1
   Host: jupiter:8100
   User-Agent: Mozilla/5.0 (Macintosh; U; PPC Mac  OS X Mach-O;
   en-US; rv:1.7.8) Gecko/20050511
   Accept:  text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,
   text/plain;q=0.8,image/png,*/*;q=0.5
   Accept-Language: en-us,en;q=0.5
   Accept-Encoding: gzip,deflate
   Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
   Keep-Alive: 300
   Connection: keep-alive
   The resource is protected,  and therefore the server will challenge for an authentication:
   HTTP/1.1 401 Authorization Required
   Date: Sun, 27 Aug 2006 14:00:05 GMT
   Server: Apache/2.0.53 (Ubuntu)  PHP/4.3.10-10ubuntu4
   WWW-Authenticate: Digest realm="Private  Domain", 
   nonce="0hvlrVH/AwA=8225d4804076a334d81181695204fee405adaaee",  
   algorithm=MD5, domain="/test",  qop="auth"
   Content-Length: 497
   Keep-Alive: timeout=15, max=100
   Connection: Keep-Alive
 Content-Type: text/html; charset=iso-8859-1

 

The client receives the HTTP error code 401 and looks for the HTTP header WWW-Authenticate. The value of HTTP WWW-Authenticate contains which authentication mechanism is being requested. In this example, HTTP digest authentication is requested. As a side note, it is possible to use basic authentication, but because it is not considered secure, it is avoided. As a response to the challenge, the browser generates a dialog box, asking for a username and password. The user types in the username and password, which causes the browser to reissue the original request with the added user authentication information, as shown here:

   GET /test/ HTTP/1.1
   Host: localhost:8100
   User-Agent: Mozilla/5.0 (Macintosh; U; PPC Mac  OS X Mach-O; 
   en-US; rv:1.7.8) Gecko/20050511
   Accept:  text/xml,application/xml,application/xhtml+xml,
   text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5
   Accept-Language: en-us,en;q=0.5
   Accept-Encoding: gzip,deflate
   Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
   Keep-Alive: 300
   Connection: keep-alive
   Authorization: Digest  username="cgross", realm="Private Domain",
   nonce="0hvlrVH/AwA=8225d4804076a334d81181695204fee405adaaee",
   uri="/test/", algorithm=MD5,
   response="fc4ec419438f87a540d8898a537ea401",  qop=auth,
 nc=00000001,  cnonce="01b6730aae57c007"

The resulting request is similar to the initial request, except that there is an additional HTTP header, Authorization. When confronted with the same URL request, the server searches for the Authorization HTTP header. If the server finds the header, the server will verify the information and then, depending on the verification, either return another HTTP 401 error, causing the browser to generate a dialog box that asks the user to authenticate himself, or consider the user authenticated. If the provided authentication information is correct, the associated representation is downloaded. When using HTTP authentication, the Authorization HTTP header is sent for all URLs and their dependents that were specified by the WWW-Authenticate header sent by the server. In this example, the value domain="/test" refers to the single URL /test and its dependencies.

Implementing HTTP Authentication

You shouldn’t write any code that manages HTTP authentication. All Web servers are capable of managing HTTP authentication, and you should leave this as an administrative exercise. This doesn’t mean that you don’t use HTTP authentication. You still need to know whether a user is authenticated, and you need to associate that user to the user identifier information. From a programmatic perspective, the authentication information is available by the server-provided request structure.

Authenticating When It Is Not Necessary

One of the side effects of HTTP authentication is that content usually is either protected or not protected. Traditionally and this is why cookies are used HTTP authentication cannot be turned off for a resource and then turned back on again for the same resource. That would confuse users, because as it stands right now, HTTP authentication is a global setting and not an individual setting. In other words, if authentication is required for one, then it is required for all. That could pose a problem. Let’s say a user is browsing a site and wants to purchase something; that user will need a shopping cart. However, a user identifier is needed to implement a shopping cart. To create a shopping cart, unprotected resources need to be protected, but the protection is global, so everybody would need to get a shopping cart after browsing the first page of a shopping site and start buying something. Nice idea to jump-start an economy, but it is not going to happen. To get around this issue of sometimes protection, you can use an HTTP authentication technique, as follows: 1. Let the user browse the site as usual (for example, http://mydomain.com/browse). 2. On each browsed page, add a protected link to indicate that the user wants to be authenticated (http://mydomain.com/browse/authenticate). 3. When the user clicks on the authentication link after the authorization, the HTTP realms (domains) that include the unprotected content are assigned in the response (http://mydomain.com/browse). 4. When the user browses the URL http://mydomain.com/browse, user identification information is sent, even though it is not required. This trick works extremely well if you use HTTP digest authentication. The following Apache HTTPD configuration example uses this technique:

   Directory "/var/www/browse/authenticate">
   AllowOverride AuthConfig
   AuthType Digest
   AuthDigestDomain /browse /browse/authenticate
   AuthDigestFile  "/etc/apache2/digestpasswd"
   AuthName "Private Domain"
   Require valid-user
 </Directory>

The technique is implemented by the configuration item AuthDigestDomain, where both the URLs /browse and /browse/authenticate are referenced. Because the configuration item Directory references the URL /browse/authenticate, only the URL /browse/authenticate will be challenged for an authentication. To illustrate that the technique actually works, consider the following HTTP conversation. First, a request is made for an unprotected resource:

   GET /browse/ HTTP/1.1
   Host: jupiter:8100
   User-Agent: Mozilla/5.0 (Windows; U; Windows NT  5.0; en-US;
   rv:1.7.5) Gecko/20041220 K-Meleon/0.9
   Accept:  text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,
   text/plain;q=0.8,image/png,*/*;q=0.5

The server responds as usual with an HTTP 200 return code, which causes the client to load the resulting page. Then the client makes another request to the protected link, because the user wants to shop and needs to be authenticated. The client makes the following request for the protected content:

   GET /browse/authenticate HTTP/1.1
   Host: 192.168.1.103:8100
   User-Agent: Mozilla/5.0 (Windows; U; Windows NT  5.0; en-US;
   rv:1.7.5) Gecko/20041220 K-Meleon/0.9
   Accept:  text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,
   text/plain;q=0.8,image/png,*/*;q=0.5
   The server responds with an  authentication challenge:
   HTTP/1.1 401 Authorization Required
   Date: Mon, 28 Aug 2006 16:08:28 GMT
   Server: Apache/2.0.53 (Ubuntu)  PHP/4.3.10-10ubuntu4
   WWW-Authenticate: Digest realm="Private  Domain", 
   nonce="yiLhlmf/AwA=e1bafc57a6151c77e1155729300132415fc8ad0c",
   algorithm=MD5, domain="/browse /browse/authenticate",
   qop="auth"
   Content-Length: 503
   Content-Type: text/html; charset=iso-8859-1
In the server response for the domain identifier, an unprotected resource is defined. This is the technique used to send authorization information for unprotected content. The client responds with user authentication, as follows:
   GET /browse/authenticate HTTP/1.1
   Host: 192.168.1.103:8100
   User-Agent: Mozilla/5.0 (Windows; U; Windows NT  5.0; en-US;
   rv:1.7.5) Gecko/20041220 K-Meleon/0.9
   Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,
   text/plain;q=0.8,image/png,*/*;q=0.5
   Authorization: Digest  username="cgross", realm="Private Domain",
   nonce="yiLhlmf/AwA=e1bafc57a6151c77e1155729300132415fc8ad0c",
   uri="/browse/authenticate",  algorithm=MD5,
   response="c9b5662c034344a06103ca745eb5ebba",  qop=auth,
   nc=00000001,  cnonce="082c875dcb2ca740"
After the authentication, the server allows the downloading of the protected content. Now if the client browses the unprotected URLs again, the authorization information is passed to the server, as illustrated by the following request:
   GET /browse/morecontent / HTTP/1.1
   Host: jupiter:8100
   User-Agent: Mozilla/5.0 (Windows; U; Windows NT  5.0; en-US;
   rv:1.7.5) Gecko/20041220 K-Meleon/0.9
   Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,
   text/plain;q=0.8,image/png,*/*;q=0.5
   Authorization: Digest  username="cgross", realm="Private Domain", 
   nonce="yiLhlmf/AwA=e1bafc57a6151c77e1155729300132415fc8ad0c",
   uri="/browse/morecontent/",  algorithm=MD5,
   response="18ccd32175ce7a3480d5fbbc24de8889",  qop=auth,
 nc=00000005,  cnonce="0d448aca73b76eb1"

For this request, the client has sent authorization information for a URL that doesn’t require authentication. Simply put, the authentication mechanism has become an “HTTP cookie” mechanism that is controlled by the client. The client is in full control of when to become authenticated and when to remain anonymous. You should remember the following points:

• The article of implementing a shopping cart or bank account involves defining an action URL and a unique URL.

• The action URL is responsible for generating a unique URL.

• You can consider the unique URL to be a personalized URL that replaces the need to keep a server-side session object.

• Server-side session objects are not useful when you want to write flexible Web services. The shopping cart examples illustrated that you can use predefined shopping carts to add value to an online store.

• You can implement the redirection from the action URL to the unique URL using the HTTP 300 series of status codes. However, using this series of status codes results in the XMLHttpRequest caller not knowing what the unique URL is.

• The preferred mechanism when using XMLHttpRequest to redirect is to use the HTTP status code 201. This code means that a new resource has been created that, from a theoretical perspective, matches the intent of the unique URL principle.

• The server generally does not track unique URLs. It is the responsibility of the client to associate a particular user with a particular unique URL. If the unique URL is anonymous, like a shopping cart, then you should use client-side cookies. If the unique URL has security restrictions, then you should use server-side cookies or HTTP authentication.

• When implementing security, you can use cookies as long as the cookies are not used to generate content. Cookies are used to authorize access to a resource.

• Cookies and HTTP authentication mechanisms are the preferred means used to implement user identification.

• When implementing the redirection functionality, you cannot cache the response from the action URL, because it will lead to data consistency problems.

• Unique URLs are processed on the server side using one of two mechanism: a predefined URL rewriting mechanism, such as Apache mod_rewrite, or the implementation of a filter that targets a specific handler. The preferred mechanism is a filter that targets a specific handler, but for legacy purposes, it is completely acceptable to use a predefined URL rewriting mechanism.

legal notice

Our website is not responsible for the information contained by this article. Web-articles is a free articles resource.
Suggestion: If you need fresh, daily updated content for your website, feel free to use our service. Click here for more information.

Useful tools and features

Link to this article from your page    Send this article to you or to a friend
If you like this article (tutorial), please link to it from your web page using the information above.

related articles

1. Ajax
Given the recent interest in Ajax, you’d be forgiven for thinking it was a new technology. In fact, the XMLHttpRequest object has been around for years. In technical terms, asynchronous JavaScript interaction with the server is nothing new. All of the other elements of the Ajax model have also been around for quite some time: CSS, (X)HTML, and DOM Scripting. Yet in 2005, interest in this methodology soared. Could it really be that simply giving this approach a snappy name like Ajax was responsible for the sudde...

2. Understanding the Definition and Philosophy of Ajax
The focus of this article is to provide solutions to some common, general problems and questions that are bound to arise before or during development of Asynchronous JavaScript and XML (Ajax) and Representational State Transfer (REST) applications. These common questions are not always technical in nature, often leaning more toward theory or philosophy of development. The problem with these kinds of questions is that once you begin to think about them, you keep going in a circle and end up where you star...

3. Understanding the Definition and Philosophy of Web Services and SOA
Understanding the Definition and Philosophy of Web Services and SOA Wikipedia offers the following definition of Web services:4 The W3C defines aWeb service as a software system designed to support interoperable machine-to-machine interaction over a network. This definition encompasses many different systems, but in common usage the term refers to those services that use SOAPformatted XML envelopes and have their interfaces described by WSDL. For ex...

4. Understanding the Definition and Philosophy of REST
Understanding the Definition and Philosophy of REST REST is a controversial topic among Web service enthusiasts, because it’s considered to stand for the opposite of what Web services and SOA are trying to achieve. The problem with this thinking is that REST is not in contradiction with the abstract definition of SOA and Web services. REST is in contradiction with technologies such as SOAP, WSDL, and WS-* specifications. The following offers a quick definition of REST:...

5. The Easiest Way to Get Started with Ajax and REST
The Easiest Way to Get Started with Ajax and REST Problem You want to know the best way to get started with writing Ajax and REST. Solution When developing an Ajax and REST application, you must decide on the tools and frameworks you’ll use. The choice is simple: Use whatever you’re using today, and write some Ajax applications. You don’t need to change the tools you’re using today. Whether you’re using ASP.NET, JavaServer Pages (JSP), PHP, Ruby, or Python, you...

6. Testing a Dynamic Contract with Ajax
Coding the Contract Using Test-Driven Development Techniques Coding the contract using agile and test-driven development techniques requires writing a number of tests and implementing aMock URL layer. Problem You want to code the contract using these development techniques. Solution To demonstrate, let’s define a use case, implement the use case as a contract, write a test case(s) to implement the contract, implement the contract in the Mock URL, and finally...

7. Testing the Client Side Logic
Problem You want to effectively test your application’s client-side logic. Theory Testing GUI code tends not to be a productive task because of the complications that arise. The main complication is how to test the correctness of a user interface. Imagine a situation where clicking a button causes a table to be filled with data. Now imagine that when a check box is checked and the button is clicked again, a different table is filled with content. The fact that clicking the same button results in two ...

8. Understanding JavaScript and Types
Understanding JavaScript and Types Problem You want to work around the fact that JavaScript does not have types declared for its variables. Theory JavaScript code does not have any variables with a declared type. The lack of typed variables is apparent when you declare functions. That said, not having typed variable declarations does not mean JavaScript has no types or no type safety. Let’s start out with the simple declaration of a function, as illustrated by the following ex...

9. Coding Using Conventions and Not Configurations
Coding Using Conventions and Not Configurations Problem You want to make your JavaScript constructs more efficient by applying the Rails “convention over configuration” principle to them. Theory You may already be familiar with the programming platform Ruby on Rails, which is used to build Web applications. The focus of this recipe is not Ruby on Rails, but one aspect of Ruby on Rails namely, convention over configuration (see http://en.wikipedia.org/wiki/ Ruby_on_Rails for m...