Module: ActionController::HttpAuthentication::Digest

### Home Classes Methods

### In Files

- lib/action_controller/metal/http_authentication.rb

### Namespace

- MODULE ActionController::HttpAuthentication::Digest::ControllerMethods

### Methods

- #authenticate
- #authentication_header
- #authentication_request
- #decode_credentials
- #decode_credentials_header
- #encode_credentials
- #expected_response
- #ha1
- #nonce
- #opaque
- #secret_token
- #validate_digest_response
- #validate_nonce

### Class/Module Index

Quicksearch

- ActionDispatch
- ActionDispatch::Assertions
- ActionDispatch::Assertions::DomAssertions
- ActionDispatch::Assertions::ResponseAssertions
- ActionDispatch::Assertions::RoutingAssertions
- ActionDispatch::Assertions::SelectorAssertions
- ActionDispatch::Assertions::TagAssertions
- ActionDispatch::BestStandardsSupport
- ActionDispatch::BodyProxy
- ActionDispatch::Callbacks
- ActionDispatch::Cookies
- ActionDispatch::Cookies::CookieOverflow
- ActionDispatch::DebugExceptions
- ActionDispatch::ExceptionWrapper
- ActionDispatch::FileHandler
- ActionDispatch::Flash
- ActionDispatch::Flash::FlashHash
- ActionDispatch::Head
- ActionDispatch::Http
- ActionDispatch::Http::Cache
- ActionDispatch::Http::Cache::Request
- ActionDispatch::Http::Cache::Response
- ActionDispatch::Http::FilterParameters
- ActionDispatch::Http::Headers
- ActionDispatch::Http::MimeNegotiation
- ActionDispatch::Http::ParameterFilter
- ActionDispatch::Http::Parameters
- ActionDispatch::Http::URL
- ActionDispatch::Http::Upload
- ActionDispatch::Http::UploadedFile
- ActionDispatch::Integration
- ActionDispatch::Integration::RequestHelpers
- ActionDispatch::Integration::Runner
- ActionDispatch::Integration::Session
- ActionDispatch::IntegrationTest
- ActionDispatch::MiddlewareStack
- ActionDispatch::MiddlewareStack::Middleware
- ActionDispatch::ParamsParser
- ActionDispatch::PerformanceTest
- ActionDispatch::PublicExceptions
- ActionDispatch::RailsEntityStore
- ActionDispatch::RailsMetaStore
- ActionDispatch::Railtie
- ActionDispatch::Reloader
- ActionDispatch::RemoteIp
- ActionDispatch::RemoteIp::GetIp
- ActionDispatch::RemoteIp::IpSpoofAttackError
- ActionDispatch::Request
- ActionDispatch::RequestId
- ActionDispatch::Rescue
- ActionDispatch::Response
- ActionDispatch::Routing
- ActionDispatch::Routing::Mapper
- ActionDispatch::Routing::Mapper::Base
- ActionDispatch::Routing::Mapper::HttpHelpers
- ActionDispatch::Routing::Mapper::Resources
- ActionDispatch::Routing::Mapper::Scoping
- ActionDispatch::Routing::PolymorphicRoutes
- ActionDispatch::Routing::Redirection
- ActionDispatch::Routing::RouteSet
- ActionDispatch::Routing::RouteSet::MountedHelpers
- ActionDispatch::Routing::UrlFor
- ActionDispatch::Session
- ActionDispatch::Session::AbstractStore
- ActionDispatch::Session::CacheStore
- ActionDispatch::Session::Compatibility
- ActionDispatch::Session::CookieStore
- ActionDispatch::Session::DestroyableSession
- ActionDispatch::Session::MemCacheStore
- ActionDispatch::Session::StaleSessionCheck
- ActionDispatch::ShowExceptions
- ActionDispatch::Static
- ActionDispatch::TestProcess
- ActionDispatch::TestRequest
- ActionDispatch::TestResponse
- ActionController
- ActionController::Base
- ActionController::Caching
- ActionController::Caching::Actions
- ActionController::Caching::Actions::ActionCachePath
- ActionController::Caching::Actions::ClassMethods
- ActionController::Caching::ConfigMethods
- ActionController::Caching::Fragments
- ActionController::Caching::Pages
- ActionController::Caching::Pages::ClassMethods
- ActionController::Caching::Sweeping
- ActionController::Compatibility
- ActionController::ConditionalGet
- ActionController::Cookies
- ActionController::DataStreaming
- ActionController::Flash
- ActionController::ForceSSL
- ActionController::ForceSSL::ClassMethods
- ActionController::Head
- ActionController::Helpers
- ActionController::Helpers::ClassMethods
- ActionController::HideActions
- ActionController::HideActions::ClassMethods
- ActionController::HttpAuthentication
- ActionController::HttpAuthentication::Basic
- ActionController::HttpAuthentication::Basic::ControllerMethods
- ActionController::HttpAuthentication::Basic::ControllerMethods::ClassMethods
- ActionController::HttpAuthentication::Digest
- ActionController::HttpAuthentication::Digest::ControllerMethods
- ActionController::HttpAuthentication::Token
- ActionController::HttpAuthentication::Token::ControllerMethods
- ActionController::ImplicitRender
- ActionController::Instrumentation
- ActionController::Instrumentation::ClassMethods
- ActionController::LogSubscriber
- ActionController::Metal
- ActionController::Middleware
- ActionController::Middleware::ActionMiddleware
- ActionController::MimeResponds
- ActionController::MimeResponds::ClassMethods
- ActionController::ParamsWrapper
- ActionController::ParamsWrapper::ClassMethods
- ActionController::RackDelegation
- ActionController::Railtie
- ActionController::Railties
- ActionController::Railties::Paths
- ActionController::RecordIdentifier
- ActionController::Redirecting
- ActionController::Renderers
- ActionController::Renderers::All
- ActionController::Renderers::ClassMethods
- ActionController::Rendering
- ActionController::RequestForgeryProtection
- ActionController::RequestForgeryProtection::ClassMethods
- ActionController::Rescue
- ActionController::Responder
- ActionController::SessionManagement
- ActionController::SessionManagement::ClassMethods
- ActionController::Streaming
- ActionController::TemplateAssertions
- ActionController::TestCase
- ActionController::TestCase::Behavior
- ActionController::TestCase::Behavior::ClassMethods
- ActionController::TestCase::RaiseActionExceptions
- ActionController::TestResponse
- ActionController::Testing
- ActionController::Testing::ClassMethods
- ActionController::UrlFor
- ActionView
- ActionView::Base
- ActionView::Context
- ActionView::FileSystemResolver
- ActionView::FixtureResolver
- ActionView::Helpers
- ActionView::Helpers::ActiveModelHelper
- ActionView::Helpers::ActiveModelInstanceTag
- ActionView::Helpers::AssetPaths
- ActionView::Helpers::AssetTagHelper
- ActionView::Helpers::AssetTagHelper::AssetIncludeTag
- ActionView::Helpers::AssetTagHelper::JavascriptIncludeTag
- ActionView::Helpers::AssetTagHelper::JavascriptTagHelpers
- ActionView::Helpers::AssetTagHelper::JavascriptTagHelpers::ClassMethods
- ActionView::Helpers::AssetTagHelper::StylesheetIncludeTag
- ActionView::Helpers::AssetTagHelper::StylesheetTagHelpers
- ActionView::Helpers::AssetTagHelper::StylesheetTagHelpers::ClassMethods
- ActionView::Helpers::AtomFeedHelper
- ActionView::Helpers::AtomFeedHelper::AtomBuilder
- ActionView::Helpers::AtomFeedHelper::AtomFeedBuilder
- ActionView::Helpers::CacheHelper
- ActionView::Helpers::CaptureHelper
- ActionView::Helpers::CsrfHelper
- ActionView::Helpers::DateHelper
- ActionView::Helpers::DateHelperInstanceTag
- ActionView::Helpers::DebugHelper
- ActionView::Helpers::FormBuilder
- ActionView::Helpers::FormHelper
- ActionView::Helpers::FormOptionsHelper
- ActionView::Helpers::FormTagHelper
- ActionView::Helpers::InstanceTag
- ActionView::Helpers::JavaScriptHelper
- ActionView::Helpers::OutputSafetyHelper
- ActionView::Helpers::RecordTagHelper
- ActionView::Helpers::RenderingHelper
- ActionView::Helpers::SanitizeHelper
- ActionView::Helpers::TagHelper
- ActionView::Helpers::TextHelper
- ActionView::Helpers::TranslationHelper
- ActionView::Helpers::UrlHelper
- ActionView::LogSubscriber
- ActionView::LookupContext
- ActionView::LookupContext::DetailsCache
- ActionView::LookupContext::ViewPaths
- ActionView::NullResolver
- ActionView::PartialRenderer
- ActionView::Railtie
- ActionView::Renderer
- ActionView::Resolver
- ActionView::Resolver::Path
- ActionView::Template
- ActionView::Template::Handlers
- ActionView::Template::Handlers::Builder
- ActionView::Template::Handlers::ERB
- ActionView::Template::Handlers::Erubis
- ActionView::TestCase
- ActionView::TestCase::Behavior
- ActionView::TestCase::Behavior::ClassMethods
- ActionView::TestCase::Behavior::Locals
- ActionView::TestCase::TestController
- AbstractController
- AbstractController::ActionNotFound
- AbstractController::AssetPaths
- AbstractController::Base
- AbstractController::Callbacks
- AbstractController::Callbacks::ClassMethods
- AbstractController::Collector
- AbstractController::DoubleRenderError
- AbstractController::Error
- AbstractController::Helpers
- AbstractController::Helpers::ClassMethods
- AbstractController::Layouts
- AbstractController::Layouts::ClassMethods
- AbstractController::Layouts::ClassMethods::LayoutConditions
- AbstractController::Logger
- AbstractController::Railties
- AbstractController::Railties::RoutesHelpers
- AbstractController::Rendering
- AbstractController::Rendering::ClassMethods
- AbstractController::Translation
- AbstractController::UrlFor
- AbstractController::UrlFor::ClassMethods
- AbstractController::ViewPaths
- AbstractController::ViewPaths::ClassMethods
- Sprockets
- Sprockets::Bootstrap
- Sprockets::Compressors
- Sprockets::Helpers
- Sprockets::Helpers::IsolatedHelper
- Sprockets::Helpers::RailsHelper
- Sprockets::Helpers::RailsHelper::AssetPaths
- Sprockets::Helpers::RailsHelper::AssetPaths::AssetNotPrecompiledError
- Sprockets::Railtie
- Sprockets::StaticCompiler
- HTML
- HTML::FullSanitizer
- HTML::LinkSanitizer
- HTML::Sanitizer
- HTML::Selector
- HTML::Tag
- HTML::WhiteListSanitizer
- Mime
- Mime::Mimes
- Mime::Type
- ActionPack
- Object
- Rack

No matching classes.

# ActionController::HttpAuthentication::Digest

### Public Instance Methods

authenticate(request, realm, &password_procedure) click to toggle source

Returns false on a valid response, true otherwise

    # File lib/action_controller/metal/http_authentication.rb, line 178
    def authenticate(request, realm, &password_procedure)
      request.authorization && validate_digest_response(request, realm, &password_procedure)
    end

authentication_header(controller, realm) click to toggle source

    # File lib/action_controller/metal/http_authentication.rb, line 236
    def authentication_header(controller, realm)
      secret_key = secret_token(controller.request)
      nonce = self.nonce(secret_key)
      opaque = opaque(secret_key)
      controller.headers["WWW-Authenticate"] = %(Digest realm="#{realm}", qop="auth", algorithm=MD5, nonce="#{nonce}", opaque="#{opaque}")
    end

authentication_request(controller, realm, message = nil) click to toggle source

    # File lib/action_controller/metal/http_authentication.rb, line 243
    def authentication_request(controller, realm, message = nil)
      message ||= "HTTP Digest: Access denied.\n"
      authentication_header(controller, realm)
      controller.response_body = message
      controller.status = 401
    end

decode_credentials(header) click to toggle source

    # File lib/action_controller/metal/http_authentication.rb, line 229
    def decode_credentials(header)
      HashWithIndifferentAccess[header.to_s.gsub(/^Digest\s+/,'').split(',').map do |pair|
        key, value = pair.split('=', 2)
        [key.strip, value.to_s.gsub(/^"|"$/,'').delete('\')]
      end]
    end

decode_credentials_header(request) click to toggle source

    # File lib/action_controller/metal/http_authentication.rb, line 225
    def decode_credentials_header(request)
      decode_credentials(request.authorization)
    end

encode_credentials(http_method, credentials, password, password_is_ha1) click to toggle source

    # File lib/action_controller/metal/http_authentication.rb, line 220
    def encode_credentials(http_method, credentials, password, password_is_ha1)
      credentials[:response] = expected_response(http_method, credentials[:uri], credentials, password, password_is_ha1)
      "Digest " + credentials.sort_by {|x| x[0].to_s }.map {|v| "#{v[0]}='#{v[1]}'" }.join(', ')
    end

expected_response(http_method, uri, credentials, password, password_is_ha1=true) click to toggle source

Returns the expected response for a request of `http_method` to `uri` with the decoded `credentials` and the expected `password` Optional parameter `password_is_ha1` is set to `true` by default, since best practice is to store ha1 digest instead of a plain-text password.

    # File lib/action_controller/metal/http_authentication.rb, line 210
    def expected_response(http_method, uri, credentials, password, password_is_ha1=true)
      ha1 = password_is_ha1 ? password : ha1(credentials, password)
      ha2 = ::Digest::MD5.hexdigest([http_method.to_s.upcase, uri].join(':'))
      ::Digest::MD5.hexdigest([ha1, credentials[:nonce], credentials[:nc], credentials[:cnonce], credentials[:qop], ha2].join(':'))
    end

ha1(credentials, password) click to toggle source

    # File lib/action_controller/metal/http_authentication.rb, line 216
    def ha1(credentials, password)
      ::Digest::MD5.hexdigest([credentials[:username], credentials[:realm], password].join(':'))
    end

nonce(secret_key, time = Time.now) click to toggle source

Uses an MD5 digest based on time to generate a value to be used only once.

A server-specified data string which should be uniquely generated each time a 401 response is made. It is recommended that this string be base64 or hexadecimal data. Specifically, since the string is passed in the header lines as a quoted string, the double-quote character is not allowed.

The contents of the nonce are implementation dependent. The quality of the implementation depends on a good choice. A nonce might, for example, be constructed as the base 64 encoding of

# > time-stamp H(time-stamp ":" ETag ":" private-key)

where time-stamp is a server-generated time or other non-repeating value, ETag is the value of the HTTP ETag header associated with the requested entity, and private-key is data known only to the server. With a nonce of this form a server would recalculate the hash portion after receiving the client authentication header and reject the request if it did not match the nonce from that header or if the time-stamp value is not recent enough. In this way the server can limit the time of the nonce's validity. The inclusion of the ETag prevents a replay request for an updated version of the resource. (Note: including the IP address of the client in the nonce would appear to offer the server the ability to limit the reuse of the nonce to the same client that originally got it. However, that would break proxy farms, where requests from a single user often go through different proxies in the farm. Also, IP address spoofing is not that hard.)

An implementation might choose not to accept a previously used nonce or a previously used digest, in order to protect against a replay attack. Or, an implementation might choose to use one-time nonces or digests for POST or PUT requests and a time-stamp for GET requests. For more details on the issues involved see Section 4 of this document.

The nonce is opaque to the client. Composed of Time, and hash of Time with secret key from the Rails session secret generated upon creation of project. Ensures the time cannot be modified by client.

    # File lib/action_controller/metal/http_authentication.rb, line 288
    def nonce(secret_key, time = Time.now)
      t = time.to_i
      hashed = [t, secret_key]
      digest = ::Digest::MD5.hexdigest(hashed.join(":"))
      ::Base64.encode64("#{t}:#{digest}").gsub("\n", '')
    end

opaque(secret_key) click to toggle source

Opaque based on random generation - but changing each request?

    # File lib/action_controller/metal/http_authentication.rb, line 306
    def opaque(secret_key)
      ::Digest::MD5.hexdigest(secret_key)
    end

secret_token(request) click to toggle source

    # File lib/action_controller/metal/http_authentication.rb, line 250
    def secret_token(request)
      secret = request.env["action_dispatch.secret_token"]
      raise "You must set config.secret_token in your app's config" if secret.blank?
      secret
    end

validate_digest_response(request, realm, &password_procedure) click to toggle source

Returns false unless the request credentials response value matches the expected value. First try the password as a ha1 digest password. If this fails, then try it as a plain text password.

    # File lib/action_controller/metal/http_authentication.rb, line 185
    def validate_digest_response(request, realm, &password_procedure)
      secret_key  = secret_token(request)
      credentials = decode_credentials_header(request)
      valid_nonce = validate_nonce(secret_key, request, credentials[:nonce])

      if valid_nonce && realm == credentials[:realm] && opaque(secret_key) == credentials[:opaque]
        password = password_procedure.call(credentials[:username])
        return false unless password

        method = request.env['rack.methodoverride.original_method'] || request.env['REQUEST_METHOD']
        uri    = credentials[:uri][0,1] == '/' ? request.original_fullpath : request.original_url

        [true, false].any? do |trailing_question_mark|
          [true, false].any? do |password_is_ha1|
            _uri = trailing_question_mark ? uri + "?" : uri
            expected = expected_response(method, _uri, credentials, password, password_is_ha1)
            expected == credentials[:response]
          end
        end
      end
    end

validate_nonce(secret_key, request, value, seconds_to_timeout=5*60) click to toggle source

Might want a shorter timeout depending on whether the request is a PUT or POST, and if client is browser or web service. Can be much shorter if the Stale directive is implemented. This would allow a user to use new nonce without prompting user again for their username and password.

    # File lib/action_controller/metal/http_authentication.rb, line 300
    def validate_nonce(secret_key, request, value, seconds_to_timeout=5*60)
      t = ::Base64.decode64(value).split(":").first.to_i
      nonce(secret_key, t) == value && (t - Time.now.to_i).abs <= seconds_to_timeout
    end

[Validate]

Generated with the Darkfish Rdoc Generator 2.