每天一剂Rails良药之open_id_authentication

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

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

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

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

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

app/views/sessions/new.rhtml:
[code]
<% 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 %>
[/code]

app/controllers/session_controller.rb:
[code]
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
[/code]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值