Hardening Devise

A few basic steps to make your Devise setup more secure lock

Send notifications for important events

Like a user changing his or her email or password. For email changes, notify the old email address to prevent quiet account takeovers (changing the email then resetting the password).

In config/initializers/devise.rb, set:

config.send_email_changed_notification = true
config.send_password_change_notification = true

Rate limit login attempts

Use Devise’s Lockable module to protect individual accounts. This will lock an account after too many attempts.

Use a library like Rack::Attack to slow down credential stuffing. This will prevent an IP address from trying to sign into many different accounts using credentials from data breaches.

Create config/initializers/rack_attack.rb with:

Rack::Attack.throttle("logins/ip", limit: 20, period: 1.hour) do |req|
  req.ip if req.post? && req.path.start_with?("/users/sign_in")

ActiveSupport::Notifications.subscribe("rack.attack") do |name, start, finish, request_id, req|
  puts "Throttled #{req.env["rack.attack.match_discriminator"]}"

Record and monitor login attempts

Use AuthTrail to record login attempts.

Remember, defense in depth!

For more, check out Secure Rails.

Published July 7, 2016 · Last updated October 30, 2018 · Tweet

You might also enjoy

Argon2 with Devise

Google OAuth with Devise

Why and How to Keep Your Decryption Keys Off Web Servers

All code examples are public domain.
Use them however you’d like (licensed under CC0).