class Rack::OpenID

A Rack middleware that provides a more HTTPish API around the ruby-openid library.

You trigger an OpenID request similar to HTTP authentication. From your app, return a “401 Unauthorized” and a “WWW-Authenticate” header with the identifier you would like to validate.

On competition, the OpenID response is automatically verified and assigned to env["rack.openid.response"].

Public Class Methods

build_header(params = {}) click to toggle source

Helper method for building the “WWW-Authenticate” header value.

Rack::OpenID.build_header(:identifier => "http://josh.openid.com/")
  #=> OpenID identifier="http://josh.openid.com/"
# File lib/rack/openid.rb, line 25
def self.build_header(params = {})
  'OpenID ' + params.map { |key, value|
    if value.is_a?(Array)
      "#{key}=\"#{value.join(',')}\""
    else
      "#{key}=\"#{value}\""
    end
  }.join(', ')
end
new(app, store = nil) click to toggle source

Initialize middleware with application and optional OpenID::Store. If no store is given, OpenID::Store::Memory is used.

use Rack::OpenID

or

use Rack::OpenID, OpenID::Store::Memcache.new
# File lib/rack/openid.rb, line 85
def initialize(app, store = nil)
  @app = app
  @store = store || default_store
end
parse_header(str) click to toggle source

Helper method for parsing “WWW-Authenticate” header values into a hash.

Rack::OpenID.parse_header("OpenID identifier='http://josh.openid.com/'")
  #=> {:identifier => "http://josh.openid.com/"}
# File lib/rack/openid.rb, line 40
def self.parse_header(str)
  params = {}
  if str =~ AUTHENTICATE_REGEXP
    str = str.gsub(%r#{AUTHENTICATE_REGEXP}\s+/, '')
    str.split(', ').each { |pair|
      key, *value = pair.split('=')
      value = value.join('=')
      value.gsub!(%r^\"/, '').gsub!(%r\"$/, "")
      value = value.split(',')
      params[key] = value.length > 1 ? value : value.first
    }
  end
  params
end

Public Instance Methods

call(env) click to toggle source

Standard Rack call dispatch that accepts an env and returns a [status, header, body] response.

# File lib/rack/openid.rb, line 92
def call(env)
  req = Rack::Request.new(env)
  if req.params["openid.mode"]
    complete_authentication(env)
  end

  status, headers, body = @app.call(env)

  qs = headers[AUTHENTICATE_HEADER]
  if status.to_i == 401 && qs && qs.match(AUTHENTICATE_REGEXP)
    begin_authentication(env, qs)
  else
    [status, headers, body]
  end
end