Failure authentication through json by sending back html instead of json

I was able to configure json authentication. I have executed the following code:

class Users:: SessionsController < Devise::SessionsController
  def create
    respond_to do |format|  
      format.html { super }  
      format.json {  
        warden.authenticate!(:scope => resource_name, :recall => "#{controller_path}#failure")  
        render :json => {:success => true}  
      }
    end  
  end

  def destroy
    respond_to do |format|
      format.html {super}
      format.json {  
        Devise.sign_out_all_scopes ? sign_out : sign_out(resource_name)
        render :json => {}
      }
    end
  end

  def failure
    render :json => {:success => false, :errors => ["Login Failed"]}
  end
end

This works fine, but when authentication fails, the failure does not return a json error. I have a custom error for development. If I remove redirect_url or completely remove the client failure, authentication will return json with an error message. My user failure looks like this:

class CustomFailure < Devise::FailureApp
  def redirect_url
    #return super unless [:worker, :employer, :user].include?(scope) #make it specific to a scope
     '/'
  end

  # You need to override respond to eliminate recall
  def respond
    if http_auth?
      http_auth
  else
    redirect
  end
end

end

In any case, to save the redirect if its an html request, and return json with an error message if its request is json?

Thank!

+5
source share
1 answer

You must tell superiors to use this custom glitch.

def failure
  respond_to do |format|
    format.html {super}
    format.json do
      warden.custom_failure!
      render :json => {:success => false, :errors => ["Login Failed"]}
    end
  end
end
+5

All Articles