我是 Rails 新手,对 Devise Gem 有相当基本的了解。除了 CRUD 和视图之外,我不清楚它提供了什么可以帮助我让 AngularJs 应用程序与 Rails Json Api 进行对话。
目前我正在用手滚动东西。为了安全起见,我在客户端(js)和服务器之间交换 HTTP 标头令牌。我还使用 Railscast #250 进行用户身份验证 - 但因为我不知道如何为远程客户端应用 SessionController。
我可以采用任何策略通过远程 json API 进行身份验证和管理会话吗?
Thanks!
我个人不会使用 devise 来做这样的事情,因为无论如何你只会使用其中的一小部分
Dont
您几乎只是不使用会话。您需要做的就是每次传递基本身份验证,并在应用程序控制器中确定其是否有效,如果不有效,则仅向它们发送回身份验证错误。
请求示例:http://username:[email protected] /cdn-cgi/l/email-protection/api/endpoint
class ApplicationController
before_filter :check_auth!
private
def check_auth!
username, password = ActionController::HttpAuthentication::Basic::user_name_and_password(request)
user = User.find_by(username: username)
if user && user.encrypted_password == SomeEncryptFunction(params[:password])
@current_user = user
else
raise "error"
end
end
end
但如果你想...
然后你可以做的是更新DateTime
当用户第一次进行身份验证(启动会话)时,他们可以只传递一个您给他们的令牌,您每次登录时都会检查该令牌。您还可以检查是否只有一定的时间自他们第一次验证以来就通过了,否则他们的会话无效。
class SessionsController < ApplicationController
skip_before_filter :check_auth!
before_filter :login!
private
# Note: I don't remember the actual devise method for validating username + password
def login!
user = User.find_by(username: params[:username])
if user && user.valid_password(params[:password])
current_user = user
current_user.update_attributes(
authenticated_at: DateTime.now,
authentication_token: Devise.friendly_token
)
else
raise "error"
end
end
end
class ApplicationController
before_filter :check_auth!
private
def check_auth!
if valid_token(params[:token])
current_user = User.find_by(authentication_token: params[:token])
else
raise "error"
end
end
# Returns true if token belongs to a user and is recent enough
def valid_token(token)
user = User.find_by(authentication_token: params[:token])
user && user.authenticated_at < DateTime.now - 1.day
end
end
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)