Rails 4 + Devise: Password Reset is always giving a "Token is invalid" error on the production server, but works fine locally.

Check the code in app/views/devise/mailer/reset_password_instructions.html.erb

The link should be generated with:

edit_password_url(@resource, :reset_password_token => @token)

If your view still uses this code, that will be the cause of the issue:

edit_password_url(@resource, :reset_password_token => @resource.password_reset_token)

Devise started storing hashes of the token, so the email needs to create the link using the real token (@token) rather than the hashed value stored in the database.

This change occurred in Devise in 143794d701


In addition to doctororange's fix, if you're overwriting resource.find_first_by_auth_conditions, you need to account for the case where warden_conditions contains a reset_password_token instead of an email or username.

EDIT: To elaborate:

Devise adds functionality to your model when you say 'devise :registerable, :trackable, ...'.

In your User model (or Admin, etc), you can overwrite the Devise method named find_first_by_auth_conditions. This special method is used by the Devise logic to locate the record that is attempting to be logged in to. Devise passes in some info in a parameter called warden_conditions. This will contain an email, a user-name, or a reset_password_token, or anything else you add to your devise log-in form (such as an account-id).

For example, you might have something that looks like this:

(app/models/user.rb)
class User

  ...

  def self.find_first_by_auth_conditions warden_conditions
    conditions = warden_conditions.dup

    if (email = conditions.delete(:email)).present?
      where(email: email.downcase).first
    end
  end

end

However, The above code will break the password-reset functionality, because devise is using a token to locate the record. The user doesn't enter an email, they enter the token via a query-string in the URL, which gets passed to this method to try and find the record.

Therefore, when you overwrite this special method you need to make it more robust to account for the password-reset case:

(app/models/user.rb)
class User

  ...

  def self.find_first_by_auth_conditions warden_conditions
    conditions = warden_conditions.dup

    if (email = conditions.delete(:email)).present?
      where(email: email.downcase).first
    elsif conditions.has_key?(:reset_password_token)
      where(reset_password_token: conditions[:reset_password_token]).first
    end
  end

end

If you are taking the URL from a log, it can appear like this:

web_1      | <p><a href=3D"http://localhost:3000/admin/password/edit?reset_password_to=
web_1      | ken=3DJ5Z5g6QNVQb3ZXkiKjTx">Change password</a></p>

In this case, using 3DJ5Z5g6QNVQb3ZXkiKjTx as the token will not work because =3D is really an = character encoded.

In this case, you need to use J5Z5g6QNVQb3ZXkiKjTx (with 3D removed)