我正在尝试使用 warden 对基于 JSON 的 API(网络服务)进行身份验证。我在 config/initializers
中将我的密码策略定义为 password_strategy.rb
,其中定义了一个 authenticate!
方法。当我从 session Controller 的创建方法中调用此 authenticate!
方法时,authenticate!
中的参数不知何故变空了,即使我可以在 session Controller 。我不确定幕后发生了什么魔法。
由于我的参数为空,我的身份验证被检测为未经授权,并且我被重定向到 session 新方法以再次登录,即使我的登录凭据是正确的。
这是我的代码:
我的POST请求URL:localhost:3000/login.json 参数:
{
"emailID":"sangam.gupta@mobiloitte.com",
"encrypted_password":"XXXXXX"
}
# Sessions controller (sessions_controller.rb)
class SessionsController < ApplicationController
skip_before_filter :authenticate!
def new
render :json => { :responseCode => "401",:responseMessage => "The email id or password you entered is incorrect. Please try again."}
end
def create
authenticate!
render :json => { :responseCode => "200",:responseMessage => "You have successfully logged in"}
end
end
# Application Controller (application_controller.rb)
require 'globals_module.rb'
class ApplicationController < ActionController::Base
include GlobalsModule
prepend_before_filter :authenticate!
helper_method :warden, :signed_in?, :current_user
around_filter :wrap_in_transaction
def wrap_in_transaction
ActiveRecord::Base.transaction do
yield
end
end
def signed_in?
!current_user.nil?
end
def current_user
warden.user
end
def warden
request.env['warden']
end
def authenticate!
Rails.logger.info params[:emailID] # email ID is present
Rails.logger.info params[:encrypted_password] #encrypted password is present
warden.authenticate!
end
end
# Password Strategy (password_strategy.rb in config/initializer)
class PasswordStrategy < Warden::Strategies::Base
def authenticate!
Rails.logger.info params # params are empty, although present before calling authenticate! method
Rails.logger.info request.session["emailID"] # It's are empty either
user = User.find_by_emailID(params[:emailID])
# my authentication code goes here
end
end
Warden::Strategies.add(:password, PasswordStrategy)
如有任何帮助,我们将不胜感激。提前致谢。
最佳答案
您需要显式调用您的 PasswordStrategy
— 通过传递您在 Warden::Strategies.add
中定义的命名符号 — 作为 authenticate 的第一个参数
,像这样:
warden.authenticate!(:password)
或者在配置 Warden::Manager 时(例如在 config/application.rb 中)将您的策略添加为默认策略:
config.middleware.insert_after(ActionDispatch::Flash, Warden::Manager) do |manager|
manager.default_strategies :password
end
参见 Warden Strategies Wiki获取完整的 API。
另请阅读 integrating Warden with Rails without Devise ,其中对 Warden 的各个部分如何组合在一起进行了详尽的解释。
关于ruby - 基于 JSON 的 API 的 Warden 身份验证),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20636185/