I am trying to authenticate using warden for JSON based APIs (web services). I have defined my password strategy inside config/initializers as password_strategy.rb which has an authenticate! method defined inside it. When I call this authenticate! method from my sessions controller's create method, parameters inside authenticate! are getting empty somehow, even though I can see my parameters inside the create method of the sessions controller. I'm not sure what magic is happening behind the scenes.
Since my parameters are empty, my authentication is detected as unauthorized and I am redirected to sessions new method for logging in again, even though my login credentials are correct.
Here is my code:
My POST request URL: localhost:3000/login.json Parameters:
{
"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)
Any help would be appreciated. Thanks in advance.