Advanced Rails - Building Industrial-Strength Web Apps in Record Time

(Tuis.) #1
Plugin Examples | 89

HTTP Authentication


The final plugin we will examine is thehttp_authenticationplugin, which allows
you to protect certain actions in an application by HTT PBasic authentication (cur-
rently,Digest authentication is stubbed out but not implemented).


The HTT PAuthentication plugin is very straightforward; the most common inter-
face is theActionControllerclass methodauthenticate_or_request_with_http_basic,
typically used in abefore_filteron protected actions. That method takes as para-
meters an authentication realm and a login procedure block that verifies the given
credentials. If the login procedure returnstrue, the action is allowed to continue. If the
login procedure returnsfalse, the action is blocked and an HTT P401 Unauthorized
status code is sent, with instructions on how to authenticate (aWWW-Authenticate
header). Inthat case, the browser will typically present the user with a login and
password and allow three tries before displaying an “Unauthorized” page.


The following is a typical use of the HTTP Authentication plugin:


class PrivateController < ApplicationController
before_filter :authenticate

def secret
render :text => "Password correct!"
end

protected

def authenticate
authenticate_or_request_with_http_basic do |username, password|
username == "bob" && password == "secret"
end
end
end

Notice that, unlike the two plugins described earlier, here we did not have to include
anything in the PrivateController—the authenticate_or_request_with_http_basic
method was already provided for us. This is because the plugin added some methods
toActionController::Base (of whichApplicationController is a subclass).


One way to include methods like this is direct monkeypatching. The plugin could
have directly written the methods intoActionController::Base:


class ActionController::Base
def authenticate_or_request_with_http_basic(realm = "Application",
&login_procedure)
authenticate_with_http_basic(&login_procedure) ||
request_http_basic_authentication(realm)
end
Free download pdf