Skip to content

Instantly share code, notes, and snippets.

@emilsoman
Last active March 3, 2021 12:49
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save emilsoman/5604254 to your computer and use it in GitHub Desktop.
Save emilsoman/5604254 to your computer and use it in GitHub Desktop.
Custom failure app to render a custom json on auth failure
class CustomAuthFailure < Devise::FailureApp
def respond
self.status = 401
self.content_type = 'json'
self.response_body = {"errors" => ["Invalid login credentials"]}.to_json
end
end
@emilsoman
Copy link
Author

And tell devise to use the custom failure app by adding the following to config/initializers/devise.rb :

  config.warden do |manager|
    manager.failure_app = CustomAuthFailure
  end 

@liushooter
Copy link

thx very good

@tyronewilson
Copy link

tyronewilson commented Sep 8, 2017

Alternative approach which I opted for after seeing this and reading Devise::FailureApp was to override the http_auth_body method instead of the respond method. I also used the inbuilt i18n_message method to populate the error field.

class FailureApp < Devise::FailureApp
  def http_auth_body
      {
          errors: [
              {
                  id: :unauthorized,
                  status: 401,
                  title: i18n_message
              }
          ]
      }.to_json
  end
end

The reason I wanted to customize the failure handling in the first place was to make the error messages comply with the JSON API standard. so that is what you are seeing here.

@Startouf
Copy link

Or see https://stackoverflow.com/questions/7297183/custom-devise-401-unauthorized-response/35299936#35299936 for a failure app that handles json and fall back to normal use otherwise

@gaboluque
Copy link

I've used this implementation and it works almost every time. The problem appears when I try to register a user with an existing email address. Rails will skip right to a PG exception. Any thoughts?

@brunobortolotti
Copy link

I've used this implementation and it works almost every time. The problem appears when I try to register a user with an existing email address. Rails will skip right to a PG exception. Any thoughts?

You're getting the PG exception probably because you're missing the validations on the User model.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment