Paul
Paul

Reputation: 26670

How to make Devise authentication respond to JSON only?

How to disable in Devise handling of HTML and XML requests and leave JSON only?

Upvotes: 10

Views: 4399

Answers (3)

Juan Manuel Maffei
Juan Manuel Maffei

Reputation: 31

You must clear_respond_to (for clear all types previously defined, like HTML or XML) and then respond_to :json in the override controller...

config/routes.rb

devise_for :users , controllers: {
  sessions: 'users/sessions',
  registrations: 'users/registrations'
}

controllers/users/sessions

class Users::SessionsController < Devise::SessionsController
    clear_respond_to 
    respond_to :json
end

controllers/users/registrations

class Users::/RegistrationsController < Devise::RegistrationsController
    clear_respond_to 
    respond_to :json
end

It works in Rails 5.2 for me!

Upvotes: 3

kravc
kravc

Reputation: 593

module DeviseOverrides
  class SessionsController < Devise::SessionsController
    # Respond only to JSON calls
    clear_respond_to
    respond_to :json
  end
end

Upvotes: 1

RobHeaton
RobHeaton

Reputation: 1390

I imagine you could override the Devise Controllers:

In controllers/devise_overrides/sessions_controller.rb:

class DeviseOverrides::SessionsController < Devise::SessionsController

  respond_to :json
  respond_to :html, only: []
  respond_to :xml, only: []

end

In routes.rb:

devise_for :users, controllers: {
  sessions:  "devise_overrides/sessions"
}

Upvotes: 8

Related Questions