Home  Contents

cgi:authenticate

Httpd/CGI Core4 Lua Event System

SYNOPSIS

success = cgi:authenticate(cgi [, realm])

DESCRIPTION

This function must be called from within the callback httpd:request(). It does basic authentication. With basic authentication, the browser asks the user for a user name and password in a pop-up dialog.

WARNING: Basic authentication does not encrypt the password. It is strongly recommended to use this method of authentication only together with SSL/TLS encrypted sessions. To make sure the session is encrypted, check that cgi.ciphersuite is non-nil. When the session is not encrypted, it is better to reject access by calling cgi:error() and exiting the callback.

The optional argument realm is a text that is displayed by the user's browser when asking for user name and password.

During authentication processing, the user's client will ask the user for a user name and password. These values are passed on to the webserver. The server will try to call back to httpd:finduser() to retrieve the password for the provided user name. The callback must return a password in hashed form as returned by cipher.crypt() or false to reject the access attempt. If the callback returns nil or does not exist, the server does default authentication.

The default authentication expects the user name to be admin. The password is read by calling kconfig.value("c4s_general", "c4t_gen_password"). This also uses the format as provided by cipher.crypt().
The Core4 Manager can be used to store an encrypted password at this location.

When authentication succeeds, the function returns true and does not send any further data to the client. Typically the application's implementation of httpd:request() lets the request progress normally.

When authentiction fails, the return value is false. A header of type 401 Not Authorized is sent to the client. Typically the application's implementation of httpd:request() simply returns from the callback and does nothing else.

Note that it is normal for a basic authentication attempt to always fail on the first try. The user's browser does not yet know that a password is required. It will learn about this when seeing the 401 response.

EXAMPLES

The simplest implementation of basic authentication is this:

function http:request() cgi:authenticate() end

This example will ask for authentication of all requests. Since there is no httpd:finduser() function, the user name must be admin and the password is found in the kconfig settings.

The next example will require authentication only when accessing the settings:

function http:request() if (cgi.request.urn:sub(1,9) == "/settings") then cgi:authenticate() end end