1
module ActionController
2
module HttpAuthentication
3
# Makes it dead easy to do HTTP Basic authentication.
5
# Simple Basic example:
7
# class PostsController < ApplicationController
8
# USER_NAME, PASSWORD = "dhh", "secret"
10
# before_filter :authenticate, :except => [ :index ]
13
# render :text => "Everyone can see me!"
17
# render :text => "I'm only accessible if you know the password"
22
# authenticate_or_request_with_http_basic do |user_name, password|
23
# user_name == USER_NAME && password == PASSWORD
29
# Here is a more advanced Basic example where only Atom feeds and the XML API is protected by HTTP authentication,
30
# the regular HTML interface is protected by a session approach:
32
# class ApplicationController < ActionController::Base
33
# before_filter :set_account, :authenticate
37
# @account = Account.find_by_url_name(request.subdomains.first)
42
# when Mime::XML, Mime::ATOM
43
# if user = authenticate_with_http_basic { |u, p| @account.users.authenticate(u, p) }
44
# @current_user = user
46
# request_http_basic_authentication
49
# if session_authenticated?
50
# @current_user = @account.users.find(session[:authenticated][:user_id])
52
# redirect_to(login_url) and return false
58
# In your integration tests, you can do something like this:
60
# def test_access_granted_from_xml
62
# "/notes/1.xml", nil,
63
# :authorization => ActionController::HttpAuthentication::Basic.encode_credentials(users(:dhh).name, users(:dhh).password)
66
# assert_equal 200, status
69
# Simple Digest example:
71
# require 'digest/md5'
72
# class PostsController < ApplicationController
73
# REALM = "SuperSecret"
74
# USERS = {"dhh" => "secret", #plain text password
75
# "dap" => Digest:MD5::hexdigest(["dap",REALM,"secret"].join(":")) #ha1 digest password
77
# before_filter :authenticate, :except => [:index]
80
# render :text => "Everyone can see me!"
84
# render :text => "I'm only accessible if you know the password"
89
# authenticate_or_request_with_http_digest(REALM) do |username|
95
# NOTE: The +authenticate_or_request_with_http_digest+ block must return the user's password or the ha1 digest hash so the framework can appropriately
96
# hash to check the user's credentials. Returning +nil+ will cause authentication to fail.
97
# Storing the ha1 hash: MD5(username:realm:password), is better than storing a plain password. If
98
# the password file or database is compromised, the attacker would be able to use the ha1 hash to
99
# authenticate as the user at this +realm+, but would not have the user's password to try using at
102
# On shared hosts, Apache sometimes doesn't pass authentication headers to
103
# FCGI instances. If your environment matches this description and you cannot
104
# authenticate, try this rule in your Apache setup:
106
# RewriteRule ^(.*)$ dispatch.fcgi [E=X-HTTP_AUTHORIZATION:%{HTTP:Authorization},QSA,L]
110
module ControllerMethods
111
def authenticate_or_request_with_http_basic(realm = "Application", &login_procedure)
112
authenticate_with_http_basic(&login_procedure) || request_http_basic_authentication(realm)
115
def authenticate_with_http_basic(&login_procedure)
116
HttpAuthentication::Basic.authenticate(self, &login_procedure)
119
def request_http_basic_authentication(realm = "Application")
120
HttpAuthentication::Basic.authentication_request(self, realm)
124
def authenticate(controller, &login_procedure)
125
unless authorization(controller.request).blank?
126
login_procedure.call(*user_name_and_password(controller.request))
130
def user_name_and_password(request)
131
decode_credentials(request).split(/:/, 2)
134
def authorization(request)
135
request.env['HTTP_AUTHORIZATION'] ||
136
request.env['X-HTTP_AUTHORIZATION'] ||
137
request.env['X_HTTP_AUTHORIZATION'] ||
138
request.env['REDIRECT_X_HTTP_AUTHORIZATION']
141
def decode_credentials(request)
142
ActiveSupport::Base64.decode64(authorization(request).split(' ', 2).last || '')
145
def encode_credentials(user_name, password)
146
"Basic #{ActiveSupport::Base64.encode64("#{user_name}:#{password}")}"
149
def authentication_request(controller, realm)
150
controller.headers["WWW-Authenticate"] = %(Basic realm="#{realm.gsub(/"/, "")}")
151
controller.__send__ :render, :text => "HTTP Basic: Access denied.\n", :status => :unauthorized
158
module ControllerMethods
159
def authenticate_or_request_with_http_digest(realm = "Application", &password_procedure)
160
authenticate_with_http_digest(realm, &password_procedure) || request_http_digest_authentication(realm)
163
# Authenticate with HTTP Digest, returns true or false
164
def authenticate_with_http_digest(realm = "Application", &password_procedure)
165
HttpAuthentication::Digest.authenticate(self, realm, &password_procedure)
168
# Render output including the HTTP Digest authentication header
169
def request_http_digest_authentication(realm = "Application", message = nil)
170
HttpAuthentication::Digest.authentication_request(self, realm, message)
174
# Returns false on a valid response, true otherwise
175
def authenticate(controller, realm, &password_procedure)
176
authorization(controller.request) && validate_digest_response(controller.request, realm, &password_procedure)
179
def authorization(request)
180
request.env['HTTP_AUTHORIZATION'] ||
181
request.env['X-HTTP_AUTHORIZATION'] ||
182
request.env['X_HTTP_AUTHORIZATION'] ||
183
request.env['REDIRECT_X_HTTP_AUTHORIZATION']
186
# Returns false unless the request credentials response value matches the expected value.
187
# First try the password as a ha1 digest password. If this fails, then try it as a plain
189
def validate_digest_response(request, realm, &password_procedure)
190
credentials = decode_credentials_header(request)
191
valid_nonce = validate_nonce(request, credentials[:nonce])
193
if valid_nonce && realm == credentials[:realm] && opaque == credentials[:opaque]
194
password = password_procedure.call(credentials[:username])
195
return false unless password
197
method = request.env['rack.methodoverride.original_method'] || request.env['REQUEST_METHOD']
198
uri = credentials[:uri][0,1] == '/' ? request.request_uri : request.url
200
[true, false].any? do |password_is_ha1|
201
expected = expected_response(method, uri, credentials, password, password_is_ha1)
202
expected == credentials[:response]
207
# Returns the expected response for a request of +http_method+ to +uri+ with the decoded +credentials+ and the expected +password+
208
# Optional parameter +password_is_ha1+ is set to +true+ by default, since best practice is to store ha1 digest instead
209
# of a plain-text password.
210
def expected_response(http_method, uri, credentials, password, password_is_ha1=true)
211
ha1 = password_is_ha1 ? password : ha1(credentials, password)
212
ha2 = ::Digest::MD5.hexdigest([http_method.to_s.upcase, uri].join(':'))
213
::Digest::MD5.hexdigest([ha1, credentials[:nonce], credentials[:nc], credentials[:cnonce], credentials[:qop], ha2].join(':'))
216
def ha1(credentials, password)
217
::Digest::MD5.hexdigest([credentials[:username], credentials[:realm], password].join(':'))
220
def encode_credentials(http_method, credentials, password, password_is_ha1)
221
credentials[:response] = expected_response(http_method, credentials[:uri], credentials, password, password_is_ha1)
222
"Digest " + credentials.sort_by {|x| x[0].to_s }.inject([]) {|a, v| a << "#{v[0]}='#{v[1]}'" }.join(', ')
225
def decode_credentials_header(request)
226
decode_credentials(authorization(request))
229
def decode_credentials(header)
230
header.to_s.gsub(/^Digest\s+/,'').split(',').inject({}.with_indifferent_access) do |hash, pair|
231
key, value = pair.split('=', 2)
232
hash[key.strip] = value.to_s.gsub(/^"|"$/,'').gsub(/'/, '')
237
def authentication_header(controller, realm)
238
controller.headers["WWW-Authenticate"] = %(Digest realm="#{realm}", qop="auth", algorithm=MD5, nonce="#{nonce}", opaque="#{opaque}")
241
def authentication_request(controller, realm, message = nil)
242
message ||= "HTTP Digest: Access denied.\n"
243
authentication_header(controller, realm)
244
controller.__send__ :render, :text => message, :status => :unauthorized
247
# Uses an MD5 digest based on time to generate a value to be used only once.
249
# A server-specified data string which should be uniquely generated each time a 401 response is made.
250
# It is recommended that this string be base64 or hexadecimal data.
251
# Specifically, since the string is passed in the header lines as a quoted string, the double-quote character is not allowed.
253
# The contents of the nonce are implementation dependent.
254
# The quality of the implementation depends on a good choice.
255
# A nonce might, for example, be constructed as the base 64 encoding of
257
# => time-stamp H(time-stamp ":" ETag ":" private-key)
259
# where time-stamp is a server-generated time or other non-repeating value,
260
# ETag is the value of the HTTP ETag header associated with the requested entity,
261
# and private-key is data known only to the server.
262
# With a nonce of this form a server would recalculate the hash portion after receiving the client authentication header and
263
# reject the request if it did not match the nonce from that header or
264
# if the time-stamp value is not recent enough. In this way the server can limit the time of the nonce's validity.
265
# The inclusion of the ETag prevents a replay request for an updated version of the resource.
266
# (Note: including the IP address of the client in the nonce would appear to offer the server the ability
267
# to limit the reuse of the nonce to the same client that originally got it.
268
# However, that would break proxy farms, where requests from a single user often go through different proxies in the farm.
269
# Also, IP address spoofing is not that hard.)
271
# An implementation might choose not to accept a previously used nonce or a previously used digest, in order to
272
# protect against a replay attack. Or, an implementation might choose to use one-time nonces or digests for
273
# POST or PUT requests and a time-stamp for GET requests. For more details on the issues involved see Section 4
276
# The nonce is opaque to the client. Composed of Time, and hash of Time with secret
277
# key from the Rails session secret generated upon creation of project. Ensures
278
# the time cannot be modifed by client.
279
def nonce(time = Time.now)
281
hashed = [t, secret_key]
282
digest = ::Digest::MD5.hexdigest(hashed.join(":"))
283
Base64.encode64("#{t}:#{digest}").gsub("\n", '')
286
# Might want a shorter timeout depending on whether the request
287
# is a PUT or POST, and if client is browser or web service.
288
# Can be much shorter if the Stale directive is implemented. This would
289
# allow a user to use new nonce without prompting user again for their
290
# username and password.
291
def validate_nonce(request, value, seconds_to_timeout=5*60)
292
return false if value.nil?
293
t = Base64.decode64(value).split(":").first.to_i
294
nonce(t) == value && (t - Time.now.to_i).abs <= seconds_to_timeout
297
# Opaque based on random generation - but changing each request?
299
::Digest::MD5.hexdigest(secret_key)
302
# Set in /initializers/session_store.rb, and loaded even if sessions are not in use.
304
ActionController::Base.session_options[:secret]