Read more

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

Arne Hartherz
April 03, 2020Software engineer at makandra GmbH

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.

Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

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 .

Posted by Arne Hartherz to makandra dev (2020-04-03 10:34)