blob: 63e7c0f06151f14fae74ef5f6ff59ed12e7bcd0a (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
|
== HTTP Authentications ==
Rails comes with two built-in HTTP authentication mechanisms :
* Basic Authentication
* Digest Authentication
=== HTTP Basic Authentication ===
HTTP Basic authentication is an authentication scheme that is supported by the majority of browsers and other HTTP clients. As an example, consider an administration section which will only be available by entering a username and a password into the browser's HTTP Basic dialog window. Using the built-in authentication is quite easy and only requires you to use one method, `authenticate_or_request_with_http_basic`.
[source, ruby]
-------------------------------------
class AdminController < ApplicationController
USERNAME, PASSWORD = "humbaba", "5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8"
before_filter :authenticate
private
def authenticate
authenticate_or_request_with_http_basic do |username, password|
username == USERNAME && Digest::SHA1.hexdigest(password) == PASSWORD
end
end
end
-------------------------------------
With this in place, you can create namespaced controllers that inherit from AdminController. The before filter will thus be run for all actions in those controllers, protecting them with HTTP Basic authentication.
=== HTTP Digest Authentication ===
HTTP Digest authentication is superior to the Basic authentication as it does not require the client to send unencrypted password over the network. Using Digest authentication with Rails is quite easy and only requires using one method, +authenticate_or_request_with_http_digest+.
[source, ruby]
-------------------------------------
class AdminController < ApplicationController
USERS = { "lifo" => "world" }
before_filter :authenticate
private
def authenticate
authenticate_or_request_with_http_digest do |username|
USERS[username]
end
end
end
-------------------------------------
As seen in the example above, +authenticate_or_request_with_http_digest+ block takes only one argument - the username. And the block returns the password. Returning +false+ or +nil+ from the +authenticate_or_request_with_http_digest+ will cause authentication failure.
|