Module: ActionController::HttpAuthentication::Token

### Home Classes Methods

### In Files

- lib/action_controller/metal/http_authentication.rb

### Namespace

- MODULE ActionController::HttpAuthentication::Token::ControllerMethods

### Methods

- #authenticate
- #authentication_request
- #encode_credentials
- #token_and_options

### 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::Token

Makes it dead easy to do HTTP Token authentication.

Simple Token example:

    class PostsController < ApplicationController
      TOKEN = "secret"

      before_filter :authenticate, :except => [ :index ]

      def index
        render :text => "Everyone can see me!"
      end

      def edit
        render :text => "I'm only accessible if you know the password"
      end

      private
        def authenticate
          authenticate_or_request_with_http_token do |token, options|
            token == TOKEN
          end
        end
    end

Here is a more advanced Token example where only Atom feeds and the XML API is protected by HTTP token authentication, the regular HTML interface is protected by a session approach:

    class ApplicationController < ActionController::Base
      before_filter :set_account, :authenticate

      protected
        def set_account
          @account = Account.find_by_url_name(request.subdomains.first)
        end

        def authenticate
          case request.format
          when Mime::XML, Mime::ATOM
            if user = authenticate_with_http_token { |t, o| @account.users.authenticate(t, o) }
              @current_user = user
            else
              request_http_token_authentication
            end
          else
            if session_authenticated?
              @current_user = @account.users.find(session[:authenticated][:user_id])
            else
              redirect_to(login_url) and return false
            end
          end
        end
    end

In your integration tests, you can do something like this:

    def test_access_granted_from_xml
      get(
        "/notes/1.xml", nil,
        :authorization => ActionController::HttpAuthentication::Token.encode_credentials(users(:dhh).token)
      )

      assert_equal 200, status
    end

On shared hosts, Apache sometimes doesn't pass authentication headers to FCGI instances. If your environment matches this description and you cannot authenticate, try this rule in your Apache setup:

    RewriteRule ^(.*)$ dispatch.fcgi [E=X-HTTP_AUTHORIZATION:%{HTTP:Authorization},QSA,L]

### Public Instance Methods

authenticate(controller, &login_procedure) click to toggle source

If token Authorization header is present, call the login procedure with the present token and options.

controller - ActionController::Base instance for the current request. login_procedure - Proc to call if a token is present. The Proc should

    take 2 arguments:
      authenticate(controller) { |token, options| ... }

Returns the return value of `&login_procedure` if a token is found. Returns nil if no token is found.

    # File lib/action_controller/metal/http_authentication.rb, line 412
    def authenticate(controller, &login_procedure)
      token, options = token_and_options(controller.request)
      unless token.blank?
        login_procedure.call(token, options)
      end
    end

authentication_request(controller, realm) click to toggle source

Sets a WWW-Authenticate to let the client know a token is desired.

controller - ActionController::Base instance for the outgoing response. realm - String realm to use in the header.

Returns nothing.

    # File lib/action_controller/metal/http_authentication.rb, line 460
    def authentication_request(controller, realm)
      controller.headers["WWW-Authenticate"] = %(Token realm="#{realm.gsub(/"/, "")}")
      controller.__send__ :render, :text => "HTTP Token: Access denied.\n", :status => :unauthorized
    end

encode_credentials(token, options = {}) click to toggle source

Encodes the given token and options into an Authorization header value.

token - String token. options - optional Hash of the options.

Returns String.

    # File lib/action_controller/metal/http_authentication.rb, line 447
    def encode_credentials(token, options = {})
      values = ["token=#{token.to_s.inspect}"] + options.map do |key, value|
        "#{key}=#{value.to_s.inspect}"
      end
      "Token #{values * ", "}"
    end

token_and_options(request) click to toggle source

Parses the token and options out of the token authorization header. If the header looks like this:

    Authorization: Token token="abc", nonce="def"

Then the returned token is "abc", and the options is {:nonce => "def"}

request - ActionDispatch::Request instance with the current headers.

Returns an Array of [String, Hash] if a token is present. Returns nil if no token is found.

    # File lib/action_controller/metal/http_authentication.rb, line 428
    def token_and_options(request)
      if request.authorization.to_s[/^Token (.*)/]
        values = Hash[$1.split(',').map do |value|
          value.strip!                      # remove any spaces between commas and values
          key, value = value.split(/\=\"?/) # split key=value pairs
          value.chomp!('"')                 # chomp trailing " in value
          value.gsub!(/\\\"/, '"')          # unescape remaining quotes
          [key, value]
        end]
        [values.delete("token"), values.with_indifferent_access]
      end
    end

[Validate]

Generated with the Darkfish Rdoc Generator 2.