原创作者: hideto   阅读:898次   评论:0条   更新时间:2011-05-26    
OpenID 是由LiveJournal和SixApart开发的一套身份验证系统。与目前流行的网站帐号系统(Passport)相比,OpenID具有开放性以及 分散式的特点。
它不基于某一应用网站的注册程序,而且不限制于单一网站的登录使用。OpenID帐号可以在任何OpenID应用网站使用,从而避免了多次 注册、填写
身份资料的繁琐过程。简单言之,OpenID就是一套以用户为中心的分散式身份验证系统,用户只需要注册获取OpenID之后,就可以凭借此 OpenID帐号
在多个网站之间自由登录使用,而不需要每上一个网站都需要注册帐号。

今天我们就来看看Rails的open_id_authentication插件

open_id_authentication是对JanRan的ruby-openid gem的封装,我们需要先安装它:
gem install ruby-openid


使用open_id_authentication时我们首先需要生成数据库表:
rake open_id_authentication:db:create


然后修改config/routes.rb:
map.open_id_complete 'session', :controller => "session", :action => "create", :requirements => {:method => :get}
map.resource :session


app/views/sessions/new.rhtml:
<% form_tag(session_url) do %>
  <p>
    <label for="name">Username:</label>
    <%= text_field_tag "name" %>
  </p>

  <p>
    <label for="password">Password:</label>
    <%= password_field_tag %>
  </p>

  <p>
    ...or use:
  </p>

  <p>
    <label for="openid_url">OpenID:</label>
    <%= text_field_tag "openid_url" %>
  </p>

  <p>
    <%= submit_tag 'Sign in' %>
  </p>
<% end %>


app/controllers/session_controller.rb:
class SessionController < ApplicationController
  def create
    if using_open_id?
      open_id_authentication
    else
      password_authentication(params[:name], params[:password])
    end
  end

  protected
    def password_authentication(name, password)
      if @current_user = @account.users.authenticate(name, password)
        successful_login
      else
        failed_login "Sorry, that username/password doesn't work"
      end
    end

    def open_id_authentication
      authenticate_with_open_id do |result, identity_url|
        if result.successful? && @current_user = @account.users.find_by_identity_url(identity_url)
          successful_login
        else
          failed_login(result.message || "Sorry, no user by that identity URL exists (#{identity_url})")
        end
      end
    end

  private
    def successful_login
      session[:user_id] = @current_user.id
      redirect_to(root_url)
    end

    def failed_login(message)
      flash[:error] = message
      redirect_to(new_session_url)
    end

end
评论 共 0 条 请登录后发表评论

发表评论

您还没有登录,请您登录后再发表评论

文章信息

Global site tag (gtag.js) - Google Analytics