1
require 'active_support/base64'
2
require 'active_support/core_ext/object/blank'
4
module ActionController
5
module HttpAuthentication
6
# Makes it dead easy to do HTTP \Basic and \Digest authentication.
8
# === Simple \Basic example
10
# class PostsController < ApplicationController
11
# http_basic_authenticate_with :name => "dhh", :password => "secret", :except => :index
14
# render :text => "Everyone can see me!"
18
# render :text => "I'm only accessible if you know the password"
22
# === Advanced \Basic example
24
# Here is a more advanced \Basic example where only Atom feeds and the XML API is protected by HTTP authentication,
25
# the regular HTML interface is protected by a session approach:
27
# class ApplicationController < ActionController::Base
28
# before_filter :set_account, :authenticate
32
# @account = Account.find_by_url_name(request.subdomains.first)
37
# when Mime::XML, Mime::ATOM
38
# if user = authenticate_with_http_basic { |u, p| @account.users.authenticate(u, p) }
39
# @current_user = user
41
# request_http_basic_authentication
44
# if session_authenticated?
45
# @current_user = @account.users.find(session[:authenticated][:user_id])
47
# redirect_to(login_url) and return false
53
# In your integration tests, you can do something like this:
55
# def test_access_granted_from_xml
57
# "/notes/1.xml", nil,
58
# 'HTTP_AUTHORIZATION' => ActionController::HttpAuthentication::Basic.encode_credentials(users(:dhh).name, users(:dhh).password)
61
# assert_equal 200, status
64
# === Simple \Digest example
66
# require 'digest/md5'
67
# class PostsController < ApplicationController
68
# REALM = "SuperSecret"
69
# USERS = {"dhh" => "secret", #plain text password
70
# "dap" => Digest::MD5.hexdigest(["dap",REALM,"secret"].join(":"))} #ha1 digest password
72
# before_filter :authenticate, :except => [:index]
75
# render :text => "Everyone can see me!"
79
# render :text => "I'm only accessible if you know the password"
84
# authenticate_or_request_with_http_digest(REALM) do |username|
92
# The +authenticate_or_request_with_http_digest+ block must return the user's password
93
# or the ha1 digest hash so the framework can appropriately hash to check the user's
94
# credentials. Returning +nil+ will cause authentication to fail.
96
# Storing the ha1 hash: MD5(username:realm:password), is better than storing a plain password. If
97
# the password file or database is compromised, the attacker would be able to use the ha1 hash to
98
# authenticate as the user at this +realm+, but would not have the user's password to try using at
101
# In rare instances, web servers or front proxies strip authorization headers before
102
# they reach your application. You can debug this situation by logging all environment
103
# variables, and check for HTTP_AUTHORIZATION, amongst others.
107
module ControllerMethods
108
extend ActiveSupport::Concern
111
def http_basic_authenticate_with(options = {})
112
before_filter(options.except(:name, :password, :realm)) do
113
authenticate_or_request_with_http_basic(options[:realm] || "Application") do |name, password|
114
name == options[:name] && password == options[:password]
120
def authenticate_or_request_with_http_basic(realm = "Application", &login_procedure)
121
authenticate_with_http_basic(&login_procedure) || request_http_basic_authentication(realm)
124
def authenticate_with_http_basic(&login_procedure)
125
HttpAuthentication::Basic.authenticate(request, &login_procedure)
128
def request_http_basic_authentication(realm = "Application")
129
HttpAuthentication::Basic.authentication_request(self, realm)
133
def authenticate(request, &login_procedure)
134
unless request.authorization.blank?
135
login_procedure.call(*user_name_and_password(request))
139
def user_name_and_password(request)
140
decode_credentials(request).split(/:/, 2)
143
def decode_credentials(request)
144
::Base64.decode64(request.authorization.split(' ', 2).last || '')
147
def encode_credentials(user_name, password)
148
"Basic #{::Base64.strict_encode64("#{user_name}:#{password}")}"
151
def authentication_request(controller, realm)
152
controller.headers["WWW-Authenticate"] = %(Basic realm="#{realm.gsub(/"/, "")}")
153
controller.response_body = "HTTP Basic: Access denied.\n"
154
controller.status = 401
161
module ControllerMethods
162
def authenticate_or_request_with_http_digest(realm = "Application", &password_procedure)
163
authenticate_with_http_digest(realm, &password_procedure) || request_http_digest_authentication(realm)
166
# Authenticate with HTTP Digest, returns true or false
167
def authenticate_with_http_digest(realm = "Application", &password_procedure)
168
HttpAuthentication::Digest.authenticate(request, realm, &password_procedure)
171
# Render output including the HTTP Digest authentication header
172
def request_http_digest_authentication(realm = "Application", message = nil)
173
HttpAuthentication::Digest.authentication_request(self, realm, message)
177
# Returns false on a valid response, true otherwise
178
def authenticate(request, realm, &password_procedure)
179
request.authorization && validate_digest_response(request, realm, &password_procedure)
182
# Returns false unless the request credentials response value matches the expected value.
183
# First try the password as a ha1 digest password. If this fails, then try it as a plain
185
def validate_digest_response(request, realm, &password_procedure)
186
secret_key = secret_token(request)
187
credentials = decode_credentials_header(request)
188
valid_nonce = validate_nonce(secret_key, request, credentials[:nonce])
190
if valid_nonce && realm == credentials[:realm] && opaque(secret_key) == credentials[:opaque]
191
password = password_procedure.call(credentials[:username])
192
return false unless password
194
method = request.env['rack.methodoverride.original_method'] || request.env['REQUEST_METHOD']
195
uri = credentials[:uri][0,1] == '/' ? request.original_fullpath : request.original_url
197
[true, false].any? do |trailing_question_mark|
198
[true, false].any? do |password_is_ha1|
199
_uri = trailing_question_mark ? uri + "?" : uri
200
expected = expected_response(method, _uri, credentials, password, password_is_ha1)
201
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 }.map {|v| "#{v[0]}='#{v[1]}'" }.join(', ')
225
def decode_credentials_header(request)
226
decode_credentials(request.authorization)
229
def decode_credentials(header)
230
Hash[header.to_s.gsub(/^Digest\s+/,'').split(',').map do |pair|
231
key, value = pair.split('=', 2)
232
[key.strip.to_sym, value.to_s.gsub(/^"|"$/,'').gsub(/'/, '')]
236
def authentication_header(controller, realm)
237
secret_key = secret_token(controller.request)
238
nonce = self.nonce(secret_key)
239
opaque = opaque(secret_key)
240
controller.headers["WWW-Authenticate"] = %(Digest realm="#{realm}", qop="auth", algorithm=MD5, nonce="#{nonce}", opaque="#{opaque}")
243
def authentication_request(controller, realm, message = nil)
244
message ||= "HTTP Digest: Access denied.\n"
245
authentication_header(controller, realm)
246
controller.response_body = message
247
controller.status = 401
250
def secret_token(request)
251
secret = request.env["action_dispatch.secret_token"]
252
raise "You must set config.secret_token in your app's config" if secret.blank?
256
# Uses an MD5 digest based on time to generate a value to be used only once.
258
# A server-specified data string which should be uniquely generated each time a 401 response is made.
259
# It is recommended that this string be base64 or hexadecimal data.
260
# Specifically, since the string is passed in the header lines as a quoted string, the double-quote character is not allowed.
262
# The contents of the nonce are implementation dependent.
263
# The quality of the implementation depends on a good choice.
264
# A nonce might, for example, be constructed as the base 64 encoding of
266
# => time-stamp H(time-stamp ":" ETag ":" private-key)
268
# where time-stamp is a server-generated time or other non-repeating value,
269
# ETag is the value of the HTTP ETag header associated with the requested entity,
270
# and private-key is data known only to the server.
271
# With a nonce of this form a server would recalculate the hash portion after receiving the client authentication header and
272
# reject the request if it did not match the nonce from that header or
273
# if the time-stamp value is not recent enough. In this way the server can limit the time of the nonce's validity.
274
# The inclusion of the ETag prevents a replay request for an updated version of the resource.
275
# (Note: including the IP address of the client in the nonce would appear to offer the server the ability
276
# to limit the reuse of the nonce to the same client that originally got it.
277
# However, that would break proxy farms, where requests from a single user often go through different proxies in the farm.
278
# Also, IP address spoofing is not that hard.)
280
# An implementation might choose not to accept a previously used nonce or a previously used digest, in order to
281
# protect against a replay attack. Or, an implementation might choose to use one-time nonces or digests for
282
# POST or PUT requests and a time-stamp for GET requests. For more details on the issues involved see Section 4
285
# The nonce is opaque to the client. Composed of Time, and hash of Time with secret
286
# key from the Rails session secret generated upon creation of project. Ensures
287
# the time cannot be modified by client.
288
def nonce(secret_key, time = Time.now)
290
hashed = [t, secret_key]
291
digest = ::Digest::MD5.hexdigest(hashed.join(":"))
292
::Base64.encode64("#{t}:#{digest}").gsub("\n", '')
295
# Might want a shorter timeout depending on whether the request
296
# is a PUT or POST, and if client is browser or web service.
297
# Can be much shorter if the Stale directive is implemented. This would
298
# allow a user to use new nonce without prompting user again for their
299
# username and password.
300
def validate_nonce(secret_key, request, value, seconds_to_timeout=5*60)
301
t = ::Base64.decode64(value).split(":").first.to_i
302
nonce(secret_key, t) == value && (t - Time.now.to_i).abs <= seconds_to_timeout
305
# Opaque based on random generation - but changing each request?
306
def opaque(secret_key)
307
::Digest::MD5.hexdigest(secret_key)
312
# Makes it dead easy to do HTTP Token authentication.
314
# Simple Token example:
316
# class PostsController < ApplicationController
319
# before_filter :authenticate, :except => [ :index ]
322
# render :text => "Everyone can see me!"
326
# render :text => "I'm only accessible if you know the password"
331
# authenticate_or_request_with_http_token do |token, options|
338
# Here is a more advanced Token example where only Atom feeds and the XML API is protected by HTTP token authentication,
339
# the regular HTML interface is protected by a session approach:
341
# class ApplicationController < ActionController::Base
342
# before_filter :set_account, :authenticate
346
# @account = Account.find_by_url_name(request.subdomains.first)
350
# case request.format
351
# when Mime::XML, Mime::ATOM
352
# if user = authenticate_with_http_token { |t, o| @account.users.authenticate(t, o) }
353
# @current_user = user
355
# request_http_token_authentication
358
# if session_authenticated?
359
# @current_user = @account.users.find(session[:authenticated][:user_id])
361
# redirect_to(login_url) and return false
368
# In your integration tests, you can do something like this:
370
# def test_access_granted_from_xml
372
# "/notes/1.xml", nil,
373
# :authorization => ActionController::HttpAuthentication::Token.encode_credentials(users(:dhh).token)
376
# assert_equal 200, status
380
# On shared hosts, Apache sometimes doesn't pass authentication headers to
381
# FCGI instances. If your environment matches this description and you cannot
382
# authenticate, try this rule in your Apache setup:
384
# RewriteRule ^(.*)$ dispatch.fcgi [E=X-HTTP_AUTHORIZATION:%{HTTP:Authorization},QSA,L]
388
module ControllerMethods
389
def authenticate_or_request_with_http_token(realm = "Application", &login_procedure)
390
authenticate_with_http_token(&login_procedure) || request_http_token_authentication(realm)
393
def authenticate_with_http_token(&login_procedure)
394
Token.authenticate(self, &login_procedure)
397
def request_http_token_authentication(realm = "Application")
398
Token.authentication_request(self, realm)
402
# If token Authorization header is present, call the login procedure with
403
# the present token and options.
405
# controller - ActionController::Base instance for the current request.
406
# login_procedure - Proc to call if a token is present. The Proc should
408
# authenticate(controller) { |token, options| ... }
410
# Returns the return value of `&login_procedure` if a token is found.
411
# Returns nil if no token is found.
412
def authenticate(controller, &login_procedure)
413
token, options = token_and_options(controller.request)
415
login_procedure.call(token, options)
419
# Parses the token and options out of the token authorization header. If
420
# the header looks like this:
421
# Authorization: Token token="abc", nonce="def"
422
# Then the returned token is "abc", and the options is {:nonce => "def"}
424
# request - ActionDispatch::Request instance with the current headers.
426
# Returns an Array of [String, Hash] if a token is present.
427
# Returns nil if no token is found.
428
def token_and_options(request)
429
if request.authorization.to_s[/^Token (.*)/]
430
values = Hash[$1.split(',').map do |value|
431
value.strip! # remove any spaces between commas and values
432
key, value = value.split(/\=\"?/) # split key=value pairs
433
value.chomp!('"') # chomp trailing " in value
434
value.gsub!(/\\\"/, '"') # unescape remaining quotes
437
[values.delete("token"), values.with_indifferent_access]
441
# Encodes the given token and options into an Authorization header value.
443
# token - String token.
444
# options - optional Hash of the options.
447
def encode_credentials(token, options = {})
448
values = ["token=#{token.to_s.inspect}"] + options.map do |key, value|
449
"#{key}=#{value.to_s.inspect}"
451
"Token #{values * ", "}"
454
# Sets a WWW-Authenticate to let the client know a token is desired.
456
# controller - ActionController::Base instance for the outgoing response.
457
# realm - String realm to use in the header.
460
def authentication_request(controller, realm)
461
controller.headers["WWW-Authenticate"] = %(Token realm="#{realm.gsub(/"/, "")}")
462
controller.__send__ :render, :text => "HTTP Token: Access denied.\n", :status => :unauthorized