0
@@ -55,7 +55,31 @@ module ActionController
0
+ # Simple Digest example. Note the block must return the user's password so the framework
0
+ # can appropriately hash it to check the user's credentials. Returning nil will cause authentication to fail.
0
+ # class PostsController < ApplicationController
0
+ # Users = {"dhh" => "secret"}
0
+ # before_filter :authenticate, :except => [ :index ]
0
+ # render :text => "Everyone can see me!"
0
+ # render :text => "I'm only accessible if you know the password"
0
+ # authenticate_or_request_with_http_digest(realm) do |user_name|
0
# In your integration tests, you can do something like this:
0
# def test_access_granted_from_xml
0
@@ -108,7 +132,10 @@ module ActionController
0
def decode_credentials(request)
0
- ActiveSupport::Base64.decode64(authorization(request).split.last || '')
0
+ # Properly decode credentials spanning a new-line
0
+ auth = authorization(request)
0
+ ActiveSupport::Base64.decode64(auth || '')
0
def encode_credentials(user_name, password)
0
@@ -120,5 +147,165 @@ module ActionController
0
controller.__send__ :render, :text => "HTTP Basic: Access denied.\n", :status => :unauthorized
0
+ module ControllerMethods
0
+ def authenticate_or_request_with_http_digest(realm = "Application", &password_procedure)
0
+ authenticate_with_http_digest!(realm, &password_procedure)
0
+ rescue ActionController::HttpAuthentication::Error => e
0
+ msg = "#{msg} expected '#{e.expected}' was '#{e.was}'" unless e.expected.nil?
0
+ request_http_digest_authentication(realm, msg)
0
+ # Authenticate using HTTP Digest, throwing ActionController::HttpAuthentication::Error on failure.
0
+ # This allows more detailed analysis of authentication failures
0
+ # to be relayed to the client.
0
+ def authenticate_with_http_digest!(realm = "Application", &login_procedure)
0
+ HttpAuthentication::Digest.authenticate(self, realm, &login_procedure)
0
+ # Authenticate with HTTP Digest, returns true or false
0
+ def authenticate_with_http_digest(realm = "Application", &login_procedure)
0
+ HttpAuthentication::Digest.authenticate(self, realm, &login_procedure) rescue false
0
+ # Render output including the HTTP Digest authentication header
0
+ def request_http_digest_authentication(realm = "Application", message = nil)
0
+ HttpAuthentication::Digest.authentication_request(self, realm, message)
0
+ # Add HTTP Digest authentication header to result headers
0
+ def http_digest_authentication_header(realm = "Application")
0
+ HttpAuthentication::Digest.authentication_header(self, realm)
0
+ # Raises error unless authentictaion succeeds, returns true otherwise
0
+ def authenticate(controller, realm, &password_procedure)
0
+ raise Error.new(false), "No authorization header found" unless authorization(controller.request)
0
+ validate_digest_response(controller, realm, &password_procedure)
0
+ def authorization(request)
0
+ request.env['HTTP_AUTHORIZATION'] ||
0
+ request.env['X-HTTP_AUTHORIZATION'] ||
0
+ request.env['X_HTTP_AUTHORIZATION'] ||
0
+ request.env['REDIRECT_X_HTTP_AUTHORIZATION']
0
+ # Raises error unless the request credentials response value matches the expected value.
0
+ def validate_digest_response(controller, realm, &password_procedure)
0
+ credentials = decode_credentials(controller.request)
0
+ # Check the nonce, opaque and realm.
0
+ # Ignore nc, as we have no way to validate the number of times this nonce has been used
0
+ validate_nonce(controller.request, credentials[:nonce])
0
+ raise Error.new(false, realm, credentials[:realm]), "Realm doesn't match" unless realm == credentials[:realm]
0
+ raise Error.new(true, opaque(controller.request), credentials[:opaque]),"Opaque doesn't match" unless opaque(controller.request) == credentials[:opaque]
0
+ password = password_procedure.call(credentials[:username])
0
+ raise Error.new(false), "No password" if password.nil?
0
+ expected = expected_response(controller.request.env['REQUEST_METHOD'], controller.request.url, credentials, password)
0
+ raise Error.new(false, expected, credentials[:response]), "Invalid response" unless expected == credentials[:response]
0
+ # Returns the expected response for a request of +http_method+ to +uri+ with the decoded +credentials+ and the expected +password+
0
+ def expected_response(http_method, uri, credentials, password)
0
+ ha1 = ::Digest::MD5.hexdigest([credentials[:username], credentials[:realm], password].join(':'))
0
+ ha2 = ::Digest::MD5.hexdigest([http_method.to_s.upcase,uri].join(':'))
0
+ ::Digest::MD5.hexdigest([ha1,credentials[:nonce], credentials[:nc], credentials[:cnonce],credentials[:qop],ha2].join(':'))
0
+ def encode_credentials(http_method, credentials, password)
0
+ credentials[:response] = expected_response(http_method, credentials[:uri], credentials, password)
0
+ "Digest " + credentials.sort_by {|x| x[0].to_s }.inject([]) {|a, v| a << "#{v[0]}='#{v[1]}'" }.join(', ')
0
+ def decode_credentials(request)
0
+ authorization(request).to_s.gsub(/^Digest\s+/,'').split(',').inject({}) do |hash, pair|
0
+ key, value = pair.split('=', 2)
0
+ hash[key.strip.to_sym] = value.to_s.gsub(/^"|"$/,'').gsub(/'/, '')
0
+ def authentication_header(controller, realm)
0
+ controller.headers["WWW-Authenticate"] = %(Digest realm="#{realm}", qop="auth", algorithm=MD5, nonce="#{nonce(controller.request)}", opaque="#{opaque(controller.request)}")
0
+ def authentication_request(controller, realm, message = "HTTP Digest: Access denied")
0
+ authentication_header(controller, realm)
0
+ controller.send! :render, :text => message, :status => :unauthorized
0
+ # Uses an MD5 digest based on time to generate a value to be used only once.
0
+ # A server-specified data string which should be uniquely generated each time a 401 response is made.
0
+ # It is recommended that this string be base64 or hexadecimal data.
0
+ # Specifically, since the string is passed in the header lines as a quoted string, the double-quote character is not allowed.
0
+ # The contents of the nonce are implementation dependent.
0
+ # The quality of the implementation depends on a good choice.
0
+ # A nonce might, for example, be constructed as the base 64 encoding of
0
+ # => time-stamp H(time-stamp ":" ETag ":" private-key)
0
+ # where time-stamp is a server-generated time or other non-repeating value,
0
+ # ETag is the value of the HTTP ETag header associated with the requested entity,
0
+ # and private-key is data known only to the server.
0
+ # With a nonce of this form a server would recalculate the hash portion after receiving the client authentication header and
0
+ # reject the request if it did not match the nonce from that header or
0
+ # if the time-stamp value is not recent enough. In this way the server can limit the time of the nonce's validity.
0
+ # The inclusion of the ETag prevents a replay request for an updated version of the resource.
0
+ # (Note: including the IP address of the client in the nonce would appear to offer the server the ability
0
+ # to limit the reuse of the nonce to the same client that originally got it.
0
+ # However, that would break proxy farms, where requests from a single user often go through different proxies in the farm.
0
+ # Also, IP address spoofing is not that hard.)
0
+ # An implementation might choose not to accept a previously used nonce or a previously used digest, in order to
0
+ # protect against a replay attack. Or, an implementation might choose to use one-time nonces or digests for
0
+ # POST or PUT requests and a time-stamp for GET requests. For more details on the issues involved see Section 4
0
+ # The nonce is opaque to the client.
0
+ def nonce(request, time = Time.now)
0
+ session_id = request.is_a?(String) ? request : request.session.session_id
0
+ hashed = [t, session_id]
0
+ digest = ::Digest::MD5.hexdigest(hashed.join(":"))
0
+ Base64.encode64("#{t}:#{digest}").gsub("\n", '')
0
+ def validate_nonce(request, value)
0
+ t = Base64.decode64(value).split(":").first.to_i
0
+ raise Error.new(true), "Stale Nonce" if (t - Time.now.to_i).abs > 10 * 60
0
+ raise Error.new(true, value, n), "Bad Nonce" unless n == value
0
+ # Opaque based on digest of session_id
0
+ session_id = request.is_a?(String) ? request : request.session.session_id
0
+ @opaque ||= Base64.encode64(::Digest::MD5::hexdigest(session_id)).gsub("\n", '')
0
+ class Error < RuntimeError
0
+ attr_accessor :expected, :was
0
+ def initialize(fatal = false, expected = nil, was = nil)
0
+ def fatal?; @fatal; end