2013-12-17 19 views
3

我正在嘗試使用基於JSON的API(Web服務)監督員進行身份驗證。我已在config/initializers內定義了我的密碼策略,其編號爲password_strategy.rb,其中定義了authenticate!方法。當我從會話控制器的create方法中調用這個authenticate!方法時,即使我可以在會話控制器的create方法內看到我的參數,authenticate!中的參數也會以某種方式變空。我不確定幕後發生了什麼魔術。對基於JSON的API的監察員身份驗證

由於我的參數是空的,我的身份驗證被檢測爲未授權,我被重定向到會話新的方法再次登錄,即使我的登錄憑證是正確的。

這裏是我的代碼:

我POST請求的URL:本地主機:3000/login.json 參數:

{ 
    "emailID":"[email protected]", 
    "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) 

任何幫助,將不勝感激。提前致謝。

+0

你的策略實際上被稱爲? – alediaferia

回答

0

您需要可以打電話給你的PasswordStrategy明確 - 通過傳遞你Warden::Strategies.add定義命名的符號 - 作爲第一個參數authenticate,像這樣:

warden.authenticate!(:password) 

或者加入你的策略作爲默認,配置時監獄長::管理器(例如,在配置/ application.rb中):

config.middleware.insert_after(ActionDispatch::Flash, Warden::Manager) do |manager| 
    manager.default_strategies :password 
end 

爲完整的API見Warden Strategies Wiki

也讀integrating Warden with Rails without Devise,它有一個徹底的解釋,如何片的監獄裝配在一起。

0

Warden正在寫入所有會話。沒有任何會話不可知的方式嗎?