Devise: How to allow only HTTP Basic Auth and disable the HTML sign-in form

Posted About 4 years ago. Visible to the public.

By default, Devise redirects to a sign-in form when accessing a route that requires authentication. If for some reason you do not want this, but use Basic Authentication (and the corresponding browser username/password dialog) instead, this is a simple change.

Note that Devise's default configuration actually only redirects requests for HTML content (as requested by the HTTP Accept header).
For all other formats (like JSON) it would use Basic Auth if the http_authenticatable setting was enabled. So you can simply enable that flag and clear the list of "navigational formats" (i.e. where a redirect makes sense) in devise.rb:

config.http_authenticatable = true
config.navigational_formats = []

You may want to also disable routes to the HTML forms in your routes.rb:

devise_for :users, skip: [:sessions] # or skip: :all to also disable password reset.

Note that forcing Basic Auth means there won't be a pretty sign-in form any more which would include a link for sign-up or password reset.
Sign-up would be easy to solve if only parts of your application require authentication (have separate links on your root page), but if users should be able to reset their passwords (why shouldn't they?), reconsider using the default approach. Also, signing out from Basic Authentication is a bit tricky Show archive.org snapshot .

Arne Hartherz
Last edit
About 4 years ago
Arne Hartherz
License
Source code in this card is licensed under the MIT License.
Posted by Arne Hartherz to makandra dev (2020-04-03 08:34)