RailsCasts - Ruby on Rails Screencasts

RailsCasts Pro episodes are now free!

Learn more or hide this

OpenID Authentication

#68 OpenID Authentication

Aug 27, 2007 | 11 minutes | Controllers, Administration, Plugins, Authentication
Ever wonder how to implement OpenID authentication in your Rails app? This episode will show you how to add it to a site with an existing authentication system.
Click to Play Video ▶
Tweet
  • Download:
  • mp4 Full Size H.264 Video (18.7 MB)
  • m4v Smaller H.264 Video (12.1 MB)
  • webm Full Size VP8 Video (40.3 MB)
  • ogv Full Size Theora Video (28.3 MB)

Resources

routes.rb
map.open_id_complete 'session', :controller => "session", :action => "create", :requirements => { :method => :get }
session_controller.rb
class SessionController < ApplicationController
 # render new.rhtml
 def new
 end
 def create
 if using_open_id?
 open_id_authentication(params[:openid_url])
 else
 password_authentication(params[:login], params[:password])
 end
 end
 def destroy
 self.current_user.forget_me if logged_in?
 cookies.delete :auth_token
 reset_session
 flash[:notice] = "You have been logged out."
 redirect_back_or_default('/')
 end
 
 protected
 
 def open_id_authentication(openid_url)
 authenticate_with_open_id(openid_url, :required => [:nickname, :email]) do |result, identity_url, registration|
 if result.successful?
 @user = User.find_or_initialize_by_identity_url(identity_url)
 if @user.new_record?
 @user.login = registration['nickname']
 @user.email = registration['email']
 @user.save(false)
 end
 self.current_user = @user
 successful_login
 else
 failed_login result.message
 end
 end
 end
 
 def password_authentication(login, password)
 self.current_user = User.authenticate(login, password)
 if logged_in?
 successful_login
 else
 failed_login
 end
 end
 
 def failed_login(message = "Authentication failed.")
 flash.now[:error] = message
 render :action => 'new'
 end
 
 def successful_login
 if params[:remember_me] == "1"
 self.current_user.remember_me
 cookies[:auth_token] = { :value => self.current_user.remember_token , :expires => self.current_user.remember_token_expires_at }
 end
 redirect_back_or_default('/')
 flash[:notice] = "Logged in successfully"
 end
end
session/new.rhtml
<label for="openid_url">OpenID URL</label><br />
<%= text_field_tag "openid_url" %>
css
/* embeds the openid image in the text field */
input#openid_url {
 background: url(http://openid.net/login-bg.gif) no-repeat;
 background-color: #fff;
 background-position: 0 50%;
 color: #000;
 padding-left: 18px;
}
loading

AltStyle によって変換されたページ (->オリジナル) /