HTTP authentication also supports bookmarking-the ability to add URLs to a list of bookmarks or favorite sites. The user can request the protected resource from the web site at a later date by selecting a bookmarked URL. If the user has not visited that site for some time, the request is challenged and the user is prompted for a username and password.
The techniques we have presented so far in this chapter can authenticate stateless applications. If you configure Apache to authenticate requests to an application's PHP scripts, no extra code needs to be written. If more authorization control is required, a function similar to the authenticateUser( )
function, shown in Example 9-7, can be included at the start of each script.
Building Session-Based Applications
Building stateful web applications requires special care because of the stateless nature of HTTP. In Chapter 8 we presented session management as a technique for building stateful applications. Many web database applications-such as on-line banking-require both authentication and session management. We now look at some of the issues that arise when building session-based applications that require user authentication.
Forcing users to a login page
Many traditional database applications require users to log in before they can perform any operations. For example, an online banking application may allow access only after a user has entered credentials from a login page. In session-based applications, forcing users to always authenticate themselves via a login script allows session variables to be registered so that the rest of the application pages operate correctly. A single point of entry can also record when users access an application or force users to view advertising.
Using HTTP authentication, if a user makes a request for a script other than the login page of the application, and the request doesn't contain the Authorization
header field, the response should redirect the user to the login page. This fragment of code sets the Location
header field, which instructs the browser to relocate to the login page if either the $PHP_AUTH_USER
or $PHP_AUTH_PW
variables aren't set:
<?php // If this is an unauthorized request, just // re-locate to the login page of the application if (!isset($PHP_AUTH_USER) || !isset($PHP_AUTH_PW)) header("Location: login.php") exit( ); // ... perform authentication and authorization ... ?> ... rest of script ...