Rack::OpenID

To view this screencast, add it to your cart and checkout. You can buy this screencast for any price, including FREE!

I was looking for an easy way to add OpenID authentication to Rack applications and I found Rack::OpenID, a Rack middleware for OpenID.

If you want to have a user redirected to their OpenID login, simply return:

1 [ 401, { 'WWW-Authenticate' => 'OpenID identity="my-open-id-url.com"' }, [] ]

If you use Rack::OpenID, that will redirect the user to login via OpenID, after which they’ll be redirected back to the URL they were redirected from with env["rack.openid.response"] set to an OpenID Response object.

Here’s a simple Rack app that using Rack::OpenID

 1 require 'rack/openid'
 2 
 3 use Rack::Session::Cookie
 4 use Rack::OpenID
 5 
 6 run lambda {|env|
 7   request = Rack::Request.new env
 8   session = env['rack.session']
 9 
10   # /logout should clear the session and redirect back to /
11   if env['PATH_INFO'] == '/logout'
12     session.clear
13     [ 302, { 'Location' => '/' }, [] ]
14 
15   # if we got a response from OpenID, save it in the session and redirect back to /
16   elsif openid_response = env['rack.openid.response']
17     session[:openid] = openid_response
18     [ 302, { 'Location' => '/' }, [] ]
19 
20   # if we POST the form (with an openid_url field), redirect the user to login via OpenID
21   elsif openid_url = request.params['openid_url']
22     [ 401, { 'WWW-Authenticate' => "OpenID identifier=\"#{ openid_url }\""}, [] ]
23 
24   # display a page with a login form and the user's current logged in status
25   else
26     if session[:openid]
27       if session[:openid].status == :failure
28         login_status = "Login Failed: #{ session[:openid].message }"
29       else
30         login_status = "Logged in as: #{ session[:openid].identity_url }"
31       end
32     end
33     [ 200, { 'Content-Type' => 'text/html' }, %{
34       <a href="/logout">Logout</a>
35       <p>#{ login_status }</p>
36       <form action="/" method="post">
37         OpenID URL: <input type="text" name="openid_url" />
38         <input type="submit" value="Login" />
39       </form>
40     } ]
41   end
42 }

http://github.com/josh/rack-openid