Devise 和 Ruby on Rails:尝试登录时如何解决“Completed 401 Unauthorized”问题

2024-04-29

我正在尝试将 Devise gem (v4.7.2) 与 Ruby on Rails (v6.0.3.2) 一起使用。

单击“登录”按钮时,我收到以下输出:

Started POST "/users/sign_in" for ::1 at 2020-11-21 18:02:54 +0000
Processing by Devise::SessionsController#create as HTML
  Parameters: {"authenticity_token"=>"3tBTwyz4dIihzNvUllHVX1b9iOzVANtyceTYQY9vfn2mHdSfmG9ivEFapBiry7I8753OCP6MrMkIVckxSGTxnQ==", "user"=>{"email"=>"[email protected] /cdn-cgi/l/email-protection", "password"=>"[FILTERED]"}}
Completed 401 Unauthorized in 1ms (ActiveRecord: 0.0ms | Allocations: 486)


Processing by Devise::SessionsController#new as HTML
  Parameters: {"authenticity_token"=>"3tBTwyz4dIihzNvUllHVX1b9iOzVANtyceTYQY9vfn2mHdSfmG9ivEFapBiry7I8753OCP6MrMkIVckxSGTxnQ==", "user"=>{"email"=>"[email protected] /cdn-cgi/l/email-protection", "password"=>"[FILTERED]"}}
  Rendering devise/sessions/new.html.erb within layouts/application
  Rendered devise/shared/_links.html.erb (Duration: 0.4ms | Allocations: 191)
  Rendered devise/sessions/new.html.erb within layouts/application (Duration: 15.9ms | Allocations: 602)
[Webpacker] Everything's up-to-date. Nothing to do
  Rendered layouts/nav/_public.html.erb (Duration: 1.2ms | Allocations: 151)
Completed 200 OK in 347ms (Views: 90.4ms | ActiveRecord: 0.0ms | Allocations: 21362)

显示“已完成 401 未经授权”,我不知道如何解决此问题。这是我的文件:

配置/初始化器/devise.rb:

# frozen_string_literal: true

# Assuming you have not yet modified this file, each configuration option below
# is set to its default value. Note that some are commented out while others
# are not: uncommented lines are intended to protect your configuration from
# breaking changes in upgrades (i.e., in the event that future versions of
# Devise change the default values for those options).
#
# Use this hook to configure devise mailer, warden hooks and so forth.
# Many of these configuration options can be set straight in your model.
Devise.setup do |config|
  # The secret key used by Devise. Devise uses this key to generate
  # random tokens. Changing this key will render invalid all existing
  # confirmation, reset password and unlock tokens in the database.
  # Devise will use the `secret_key_base` as its `secret_key`
  # by default. You can change it below and use your own secret key.
  # config.secret_key = '###'

  # ==> Controller configuration
  # Configure the parent class to the devise controllers.
  # config.parent_controller = 'DeviseController'

  # ==> Mailer Configuration
  # Configure the e-mail address which will be shown in Devise::Mailer,
  # note that it will be overwritten if you use your own mailer class
  # with default "from" parameter.
  config.mailer_sender = '[email protected] /cdn-cgi/l/email-protection'

  # Configure the class responsible to send e-mails.
  # config.mailer = 'Devise::Mailer'

  # Configure the parent class responsible to send e-mails.
  # config.parent_mailer = 'ActionMailer::Base'

  # ==> ORM configuration
  # Load and configure the ORM. Supports :active_record (default) and
  # :mongoid (bson_ext recommended) by default. Other ORMs may be
  # available as additional gems.
  require 'devise/orm/active_record'

  # ==> Configuration for any authentication mechanism
  # Configure which keys are used when authenticating a user. The default is
  # just :email. You can configure it to use [:username, :subdomain], so for
  # authenticating a user, both parameters are required. Remember that those
  # parameters are used only when authenticating and not when retrieving from
  # session. If you need permissions, you should implement that in a before filter.
  # You can also supply a hash where the value is a boolean determining whether
  # or not authentication should be aborted when the value is not present.
  # config.authentication_keys = [:email]
  config.authentication_keys = [ :login ]

  # Configure parameters from the request object used for authentication. Each entry
  # given should be a request method and it will automatically be passed to the
  # find_for_authentication method and considered in your model lookup. For instance,
  # if you set :request_keys to [:subdomain], :subdomain will be used on authentication.
  # The same considerations mentioned for authentication_keys also apply to request_keys.
  # config.request_keys = []

  # Configure which authentication keys should be case-insensitive.
  # These keys will be downcased upon creating or modifying a user and when used
  # to authenticate or find a user. Default is :email.
  config.case_insensitive_keys = [:email]

  # Configure which authentication keys should have whitespace stripped.
  # These keys will have whitespace before and after removed upon creating or
  # modifying a user and when used to authenticate or find a user. Default is :email.
  config.strip_whitespace_keys = [:email]

  # Tell if authentication through request.params is enabled. True by default.
  # It can be set to an array that will enable params authentication only for the
  # given strategies, for example, `config.params_authenticatable = [:database]` will
  # enable it only for database (email + password) authentication.
  # config.params_authenticatable = true

  # Tell if authentication through HTTP Auth is enabled. False by default.
  # It can be set to an array that will enable http authentication only for the
  # given strategies, for example, `config.http_authenticatable = [:database]` will
  # enable it only for database authentication.
  # For API-only applications to support authentication "out-of-the-box", you will likely want to
  # enable this with :database unless you are using a custom strategy.
  # The supported strategies are:
  # :database      = Support basic authentication with authentication key + password
  # config.http_authenticatable = false

  # If 401 status code should be returned for AJAX requests. True by default.
  # config.http_authenticatable_on_xhr = true

  # The realm used in Http Basic Authentication. 'Application' by default.
  # config.http_authentication_realm = 'Application'

  # It will change confirmation, password recovery and other workflows
  # to behave the same regardless if the e-mail provided was right or wrong.
  # Does not affect registerable.
  # config.paranoid = true

  # By default Devise will store the user in session. You can skip storage for
  # particular strategies by setting this option.
  # Notice that if you are skipping storage for all authentication paths, you
  # may want to disable generating routes to Devise's sessions controller by
  # passing skip: :sessions to `devise_for` in your config/routes.rb
  config.skip_session_storage = [:http_auth]

  # By default, Devise cleans up the CSRF token on authentication to
  # avoid CSRF token fixation attacks. This means that, when using AJAX
  # requests for sign in and sign up, you need to get a new CSRF token
  # from the server. You can disable this option at your own risk.
  # config.clean_up_csrf_token_on_authentication = true

  # When false, Devise will not attempt to reload routes on eager load.
  # This can reduce the time taken to boot the app but if your application
  # requires the Devise mappings to be loaded during boot time the application
  # won't boot properly.
  # config.reload_routes = true

  # ==> Configuration for :database_authenticatable
  # For bcrypt, this is the cost for hashing the password and defaults to 12. If
  # using other algorithms, it sets how many times you want the password to be hashed.
  # The number of stretches used for generating the hashed password are stored
  # with the hashed password. This allows you to change the stretches without
  # invalidating existing passwords.
  #
  # Limiting the stretches to just one in testing will increase the performance of
  # your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use
  # a value less than 10 in other environments. Note that, for bcrypt (the default
  # algorithm), the cost increases exponentially with the number of stretches (e.g.
  # a value of 20 is already extremely slow: approx. 60 seconds for 1 calculation).
  config.stretches = Rails.env.test? ? 1 : 12

  # Set up a pepper to generate the hashed password.
  # config.pepper = '###'

  # Send a notification to the original email when the user's email is changed.
  # config.send_email_changed_notification = false

  # Send a notification email when the user's password is changed.
  # config.send_password_change_notification = false

  # ==> Configuration for :confirmable
  # A period that the user is allowed to access the website even without
  # confirming their account. For instance, if set to 2.days, the user will be
  # able to access the website for two days without confirming their account,
  # access will be blocked just in the third day.
  # You can also set it to nil, which will allow the user to access the website
  # without confirming their account.
  # Default is 0.days, meaning the user cannot access the website without
  # confirming their account.
  # config.allow_unconfirmed_access_for = 2.days

  # A period that the user is allowed to confirm their account before their
  # token becomes invalid. For example, if set to 3.days, the user can confirm
  # their account within 3 days after the mail was sent, but on the fourth day
  # their account can't be confirmed with the token any more.
  # Default is nil, meaning there is no restriction on how long a user can take
  # before confirming their account.
  # config.confirm_within = 3.days

  # If true, requires any email changes to be confirmed (exactly the same way as
  # initial account confirmation) to be applied. Requires additional unconfirmed_email
  # db field (see migrations). Until confirmed, new email is stored in
  # unconfirmed_email column, and copied to email column on successful confirmation.
  config.reconfirmable = true

  # Defines which key will be used when confirming an account
  # config.confirmation_keys = [:email]

  # ==> Configuration for :rememberable
  # The time the user will be remembered without asking for credentials again.
  # config.remember_for = 2.weeks

  # Invalidates all the remember me tokens when the user signs out.
  config.expire_all_remember_me_on_sign_out = true

  # If true, extends the user's remember period when remembered via cookie.
  # config.extend_remember_period = false

  # Options to be passed to the created cookie. For instance, you can set
  # secure: true in order to force SSL only cookies.
  # config.rememberable_options = {}

  # ==> Configuration for :validatable
  # Range for password length.
  config.password_length = 6..128

  # Email regex used to validate email formats. It simply asserts that
  # one (and only one) @ exists in the given string. This is mainly
  # to give user feedback and not to assert the e-mail validity.
  config.email_regexp = /\A[^@\s]+@[^@\s]+\z/

  # ==> Configuration for :timeoutable
  # The time you want to timeout the user session without activity. After this
  # time the user will be asked for credentials again. Default is 30 minutes.
  # config.timeout_in = 30.minutes

  # ==> Configuration for :lockable
  # Defines which strategy will be used to lock an account.
  # :failed_attempts = Locks an account after a number of failed attempts to sign in.
  # :none            = No lock strategy. You should handle locking by yourself.
  # config.lock_strategy = :failed_attempts

  # Defines which key will be used when locking and unlocking an account
  # config.unlock_keys = [:email]

  # Defines which strategy will be used to unlock an account.
  # :email = Sends an unlock link to the user email
  # :time  = Re-enables login after a certain amount of time (see :unlock_in below)
  # :both  = Enables both strategies
  # :none  = No unlock strategy. You should handle unlocking by yourself.
  # config.unlock_strategy = :both

  # Number of authentication tries before locking an account if lock_strategy
  # is failed attempts.
  # config.maximum_attempts = 20

  # Time interval to unlock the account if :time is enabled as unlock_strategy.
  # config.unlock_in = 1.hour

  # Warn on the last attempt before the account is locked.
  # config.last_attempt_warning = true

  # ==> Configuration for :recoverable
  #
  # Defines which key will be used when recovering the password for an account
  # config.reset_password_keys = [:email]

  # Time interval you can reset your password with a reset password key.
  # Don't put a too small interval or your users won't have the time to
  # change their passwords.
  config.reset_password_within = 6.hours

  # When set to false, does not sign a user in automatically after their password is
  # reset. Defaults to true, so a user is signed in automatically after a reset.
  # config.sign_in_after_reset_password = true

  # ==> Configuration for :encryptable
  # Allow you to use another hashing or encryption algorithm besides bcrypt (default).
  # You can use :sha1, :sha512 or algorithms from others authentication tools as
  # :clearance_sha1, :authlogic_sha512 (then you should set stretches above to 20
  # for default behavior) and :restful_authentication_sha1 (then you should set
  # stretches to 10, and copy REST_AUTH_SITE_KEY to pepper).
  #
  # Require the `devise-encryptable` gem when using anything other than bcrypt
  # config.encryptor = :sha512

  # ==> Scopes configuration
  # Turn scoped views on. Before rendering "sessions/new", it will first check for
  # "users/sessions/new". It's turned off by default because it's slower if you
  # are using only default views.
  # config.scoped_views = false

  # Configure the default scope given to Warden. By default it's the first
  # devise role declared in your routes (usually :user).
  # config.default_scope = :user

  # Set this configuration to false if you want /users/sign_out to sign out
  # only the current scope. By default, Devise signs out all scopes.
  # config.sign_out_all_scopes = true

  # ==> Navigation configuration
  # Lists the formats that should be treated as navigational. Formats like
  # :html, should redirect to the sign in page when the user does not have
  # access, but formats like :xml or :json, should return 401.
  #
  # If you have any extra navigational formats, like :iphone or :mobile, you
  # should add them to the navigational formats lists.
  #
  # The "*/*" below is required to match Internet Explorer requests.
  # config.navigational_formats = ['*/*', :html]

  # The default HTTP method used to sign out a resource. Default is :delete.
  config.sign_out_via = :delete

  # ==> OmniAuth
  # Add a new OmniAuth provider. Check the wiki for more information on setting
  # up on your models and hooks.
  # config.omniauth :github, 'APP_ID', 'APP_SECRET', scope: 'user,public_repo'

  # ==> Warden configuration
  # If you want to use other strategies, that are not supported by Devise, or
  # change the failure app, you can configure them inside the config.warden block.
  #
  # config.warden do |manager|
  #   manager.intercept_401 = false
  #   manager.default_strategies(scope: :user).unshift :some_external_strategy
  # end

  # ==> Mountable engine configurations
  # When using Devise inside an engine, let's call it `MyEngine`, and this engine
  # is mountable, there are some extra configurations to be taken into account.
  # The following options are available, assuming the engine is mounted as:
  #
  #     mount MyEngine, at: '/my_engine'
  #
  # The router that invoked `devise_for`, in the example above, would be:
  # config.router_name = :my_engine
  #
  # When using OmniAuth, Devise cannot automatically set OmniAuth path,
  # so you need to do it manually. For the users scope, it would be:
  # config.omniauth_path_prefix = '/my_engine/users/auth'

  # ==> Turbolinks configuration
  # If your app is using Turbolinks, Turbolinks::Controller needs to be included to make redirection work correctly:
  #
  # ActiveSupport.on_load(:devise_failure_app) do
  #   include Turbolinks::Controller
  # end

  # ==> Configuration for :registerable

  # When set to false, does not sign a user in automatically after their password is
  # changed. Defaults to true, so a user is signed in automatically after changing a password.
  # config.sign_in_after_change_password = true
end

模型/用户.rb

class User < ApplicationRecord

  devise :database_authenticatable, :registerable,
  :recoverable, :rememberable, :trackable, 
  :validatable, :confirmable, authentication_keys: [:login]

  # Create relationship - User has many properties.
  has_many :properties

  attr_writer :login

  def login
    @login || self.username || self.email
  end

end

控制器/application_controller.rb:

class ApplicationController < ActionController::Base

    protect_from_forgery prepend: true
    
    before_action :configure_permitted_parameters, if: :devise_controller?

    def index
    end

    protected

    # Restrict parameters for sign up input.
    def configure_permitted_parameters
        added_attrs = [:first_name, :last_name, :email, :password, :password_confirmation, :remember_me]
        devise_parameter_sanitizer.permit :sign_up, keys: added_attrs
        devise_parameter_sanitizer.permit :account_update, keys: added_attrs
        devise_parameter_sanitizer.permit :sign_in, keys: added_attrs
    end

end

控制器/用户/sessions_controller.rb:

# frozen_string_literal: true

class Users::SessionsController < Devise::SessionsController
  # before_action :configure_sign_in_params, only: [:create]

  # GET /resource/sign_in
  # def new
  #   super
  # end

  # POST /resource/sign_in
  # def create
  #   super
  # end

  # DELETE /resource/sign_out
  # def destroy
  #   super
  # end

  # protected

  # If you have extra params to permit, append them to the sanitizer.
  # def configure_sign_in_params
  #   devise_parameter_sanitizer.permit(:sign_in, keys: [:attribute])
  # end
end

视图/设计/会话/new.html.erb:

<section class="form-auth text-center">
  <%= form_for(resource, as: resource_name, url: session_path(resource_name)) do |f| %>
    <!-- <img class="mb-4" src="" alt="" width="72" height="72"> -->
    <h1 class="h3 mb-3 font-weight-normal">Please Log In</h1>

    <label for="inputEmail" class="sr-only">Email address</label>
    <%= f.email_field :email, autofocus: true, class: "form-control", id: "inputEmail", placeholder: "Email address", autocomplete: "current-email", required: "" %>

    <label for="inputPassword" class="sr-only">Password</label>
    <%= f.password_field :password, autocomplete: "current-password", placeholder: "Password", class: "form-control", id: "inputPassword", required: "" %>
    
    <div class="checkbox mb-3">
      <label>
        <input type="checkbox" value="remember-me"> Remember me
      </label>
    </div>
    
    <button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
    <p class="mt-5 mb-3 text-muted">&copy; 2020</p>

  <% end %>

  <%= render "devise/shared/links" %>

</section>

感谢任何帮助。


我解决了这个问题,我的工作代码如下。

主要问题是我在清理参数时在 configure_permissed_pa​​rameters 函数中传递了错误的参数。我是路过的:password但这本应该是:encrypted_password。见下文。

# Restrict parameters for sign up input.
    def configure_permitted_parameters
        added_attrs = [:first_name, :last_name, :email, :encrypted_password, :password_confirmation, :remember_me]
        devise_parameter_sanitizer.permit(:sign_up, keys: added_attrs)
        devise_parameter_sanitizer.permit(:account_update, keys: added_attrs)
        devise_parameter_sanitizer.permit(:sign_in, keys: added_attrs)
    end

参数/属性:encrypted_password正在清理的内容显示在 db/migrate/xxxxxxxxxxxxxx_devise_create_users.rb 迁移文件中:

# frozen_string_literal: true

class DeviseCreateUsers < ActiveRecord::Migration[6.0]
  def change
    create_table :users do |t|
      ## Database authenticatable
      t.string :first_name,         null: false, default: ""
      t.string :last_name,          null: false, default: ""
      t.string :email,              null: false, default: ""
      t.string :encrypted_password, null: false, default: ""
      t.string :url

      ## Recoverable
      t.string   :reset_password_token
      t.datetime :reset_password_sent_at

      ## Rememberable
      t.datetime :remember_created_at

      ## Trackable
      t.integer  :sign_in_count, default: 0, null: false
      t.datetime :current_sign_in_at
      t.datetime :last_sign_in_at
      t.inet     :current_sign_in_ip
      t.inet     :last_sign_in_ip

      ## Confirmable
      t.string   :confirmation_token
      t.datetime :confirmed_at
      t.datetime :confirmation_sent_at
      t.string   :unconfirmed_email # Only if using reconfirmable

      ## Lockable
      # t.integer  :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts
      # t.string   :unlock_token # Only if unlock strategy is :email or :both
      # t.datetime :locked_at


      t.timestamps null: false
    end

    add_index :users, :email,                unique: true
    add_index :users, :reset_password_token, unique: true
    add_index :users, :confirmation_token,   unique: true
    # add_index :users, :unlock_token,         unique: true
  end
end

该问题的其他文件如下供参考:

下面的 config/initializers/devise.rb :

# frozen_string_literal: true

# Assuming you have not yet modified this file, each configuration option below
# is set to its default value. Note that some are commented out while others
# are not: uncommented lines are intended to protect your configuration from
# breaking changes in upgrades (i.e., in the event that future versions of
# Devise change the default values for those options).
#
# Use this hook to configure devise mailer, warden hooks and so forth.
# Many of these configuration options can be set straight in your model.
Devise.setup do |config|
  # The secret key used by Devise. Devise uses this key to generate
  # random tokens. Changing this key will render invalid all existing
  # confirmation, reset password and unlock tokens in the database.
  # Devise will use the `secret_key_base` as its `secret_key`
  # by default. You can change it below and use your own secret key.
  # config.secret_key = 'INSERT YOUR SECREY KEY HERE'

  # ==> Controller configuration
  # Configure the parent class to the devise controllers.
  # config.parent_controller = 'DeviseController'

  # ==> Mailer Configuration
  # Configure the e-mail address which will be shown in Devise::Mailer,
  # note that it will be overwritten if you use your own mailer class
  # with default "from" parameter.
  config.mailer_sender = '[email protected] /cdn-cgi/l/email-protection'

  # Configure the class responsible to send e-mails.
  # config.mailer = 'Devise::Mailer'

  # Configure the parent class responsible to send e-mails.
  # config.parent_mailer = 'ActionMailer::Base'

  # ==> ORM configuration
  # Load and configure the ORM. Supports :active_record (default) and
  # :mongoid (bson_ext recommended) by default. Other ORMs may be
  # available as additional gems.
  require 'devise/orm/active_record'

  # ==> Configuration for any authentication mechanism
  # Configure which keys are used when authenticating a user. The default is
  # just :email. You can configure it to use [:username, :subdomain], so for
  # authenticating a user, both parameters are required. Remember that those
  # parameters are used only when authenticating and not when retrieving from
  # session. If you need permissions, you should implement that in a before filter.
  # You can also supply a hash where the value is a boolean determining whether
  # or not authentication should be aborted when the value is not present.
  # config.authentication_keys = [:email]
  # config.authentication_keys = [ :login ]

  # Configure parameters from the request object used for authentication. Each entry
  # given should be a request method and it will automatically be passed to the
  # find_for_authentication method and considered in your model lookup. For instance,
  # if you set :request_keys to [:subdomain], :subdomain will be used on authentication.
  # The same considerations mentioned for authentication_keys also apply to request_keys.
  # config.request_keys = []

  # Configure which authentication keys should be case-insensitive.
  # These keys will be downcased upon creating or modifying a user and when used
  # to authenticate or find a user. Default is :email.
  config.case_insensitive_keys = [:email]

  # Configure which authentication keys should have whitespace stripped.
  # These keys will have whitespace before and after removed upon creating or
  # modifying a user and when used to authenticate or find a user. Default is :email.
  config.strip_whitespace_keys = [:email]

  # Tell if authentication through request.params is enabled. True by default.
  # It can be set to an array that will enable params authentication only for the
  # given strategies, for example, `config.params_authenticatable = [:database]` will
  # enable it only for database (email + password) authentication.
  # config.params_authenticatable = true

  # Tell if authentication through HTTP Auth is enabled. False by default.
  # It can be set to an array that will enable http authentication only for the
  # given strategies, for example, `config.http_authenticatable = [:database]` will
  # enable it only for database authentication.
  # For API-only applications to support authentication "out-of-the-box", you will likely want to
  # enable this with :database unless you are using a custom strategy.
  # The supported strategies are:
  # :database      = Support basic authentication with authentication key + password
  # config.http_authenticatable = false

  # If 401 status code should be returned for AJAX requests. True by default.
  # config.http_authenticatable_on_xhr = true

  # The realm used in Http Basic Authentication. 'Application' by default.
  # config.http_authentication_realm = 'Application'

  # It will change confirmation, password recovery and other workflows
  # to behave the same regardless if the e-mail provided was right or wrong.
  # Does not affect registerable.
  # config.paranoid = true

  # By default Devise will store the user in session. You can skip storage for
  # particular strategies by setting this option.
  # Notice that if you are skipping storage for all authentication paths, you
  # may want to disable generating routes to Devise's sessions controller by
  # passing skip: :sessions to `devise_for` in your config/routes.rb
  config.skip_session_storage = [:http_auth]

  # By default, Devise cleans up the CSRF token on authentication to
  # avoid CSRF token fixation attacks. This means that, when using AJAX
  # requests for sign in and sign up, you need to get a new CSRF token
  # from the server. You can disable this option at your own risk.
  # config.clean_up_csrf_token_on_authentication = true

  # When false, Devise will not attempt to reload routes on eager load.
  # This can reduce the time taken to boot the app but if your application
  # requires the Devise mappings to be loaded during boot time the application
  # won't boot properly.
  # config.reload_routes = true

  # ==> Configuration for :database_authenticatable
  # For bcrypt, this is the cost for hashing the password and defaults to 12. If
  # using other algorithms, it sets how many times you want the password to be hashed.
  # The number of stretches used for generating the hashed password are stored
  # with the hashed password. This allows you to change the stretches without
  # invalidating existing passwords.
  #
  # Limiting the stretches to just one in testing will increase the performance of
  # your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use
  # a value less than 10 in other environments. Note that, for bcrypt (the default
  # algorithm), the cost increases exponentially with the number of stretches (e.g.
  # a value of 20 is already extremely slow: approx. 60 seconds for 1 calculation).
  config.stretches = Rails.env.test? ? 1 : 12

  # Set up a pepper to generate the hashed password.
  # config.pepper = 'xxx'

  # Send a notification to the original email when the user's email is changed.
  # config.send_email_changed_notification = false

  # Send a notification email when the user's password is changed.
  # config.send_password_change_notification = false

  # ==> Configuration for :confirmable
  # A period that the user is allowed to access the website even without
  # confirming their account. For instance, if set to 2.days, the user will be
  # able to access the website for two days without confirming their account,
  # access will be blocked just in the third day.
  # You can also set it to nil, which will allow the user to access the website
  # without confirming their account.
  # Default is 0.days, meaning the user cannot access the website without
  # confirming their account.
  # config.allow_unconfirmed_access_for = 2.days

  # A period that the user is allowed to confirm their account before their
  # token becomes invalid. For example, if set to 3.days, the user can confirm
  # their account within 3 days after the mail was sent, but on the fourth day
  # their account can't be confirmed with the token any more.
  # Default is nil, meaning there is no restriction on how long a user can take
  # before confirming their account.
  # config.confirm_within = 3.days

  # If true, requires any email changes to be confirmed (exactly the same way as
  # initial account confirmation) to be applied. Requires additional unconfirmed_email
  # db field (see migrations). Until confirmed, new email is stored in
  # unconfirmed_email column, and copied to email column on successful confirmation.
  config.reconfirmable = true

  # Defines which key will be used when confirming an account
  # config.confirmation_keys = [:email]

  # ==> Configuration for :rememberable
  # The time the user will be remembered without asking for credentials again.
  # config.remember_for = 2.weeks

  # Invalidates all the remember me tokens when the user signs out.
  config.expire_all_remember_me_on_sign_out = true

  # If true, extends the user's remember period when remembered via cookie.
  # config.extend_remember_period = false

  # Options to be passed to the created cookie. For instance, you can set
  # secure: true in order to force SSL only cookies.
  # config.rememberable_options = {}

  # ==> Configuration for :validatable
  # Range for password length.
  config.password_length = 6..128

  # Email regex used to validate email formats. It simply asserts that
  # one (and only one) @ exists in the given string. This is mainly
  # to give user feedback and not to assert the e-mail validity.
  config.email_regexp = /\A[^@\s]+@[^@\s]+\z/

  # ==> Configuration for :timeoutable
  # The time you want to timeout the user session without activity. After this
  # time the user will be asked for credentials again. Default is 30 minutes.
  # config.timeout_in = 30.minutes

  # ==> Configuration for :lockable
  # Defines which strategy will be used to lock an account.
  # :failed_attempts = Locks an account after a number of failed attempts to sign in.
  # :none            = No lock strategy. You should handle locking by yourself.
  # config.lock_strategy = :failed_attempts

  # Defines which key will be used when locking and unlocking an account
  # config.unlock_keys = [:email]

  # Defines which strategy will be used to unlock an account.
  # :email = Sends an unlock link to the user email
  # :time  = Re-enables login after a certain amount of time (see :unlock_in below)
  # :both  = Enables both strategies
  # :none  = No unlock strategy. You should handle unlocking by yourself.
  # config.unlock_strategy = :both

  # Number of authentication tries before locking an account if lock_strategy
  # is failed attempts.
  # config.maximum_attempts = 20

  # Time interval to unlock the account if :time is enabled as unlock_strategy.
  # config.unlock_in = 1.hour

  # Warn on the last attempt before the account is locked.
  # config.last_attempt_warning = true

  # ==> Configuration for :recoverable
  #
  # Defines which key will be used when recovering the password for an account
  # config.reset_password_keys = [:email]

  # Time interval you can reset your password with a reset password key.
  # Don't put a too small interval or your users won't have the time to
  # change their passwords.
  config.reset_password_within = 6.hours

  # When set to false, does not sign a user in automatically after their password is
  # reset. Defaults to true, so a user is signed in automatically after a reset.
  # config.sign_in_after_reset_password = true

  # ==> Configuration for :encryptable
  # Allow you to use another hashing or encryption algorithm besides bcrypt (default).
  # You can use :sha1, :sha512 or algorithms from others authentication tools as
  # :clearance_sha1, :authlogic_sha512 (then you should set stretches above to 20
  # for default behavior) and :restful_authentication_sha1 (then you should set
  # stretches to 10, and copy REST_AUTH_SITE_KEY to pepper).
  #
  # Require the `devise-encryptable` gem when using anything other than bcrypt
  # config.encryptor = :sha512

  # ==> Scopes configuration
  # Turn scoped views on. Before rendering "sessions/new", it will first check for
  # "users/sessions/new". It's turned off by default because it's slower if you
  # are using only default views.
  # config.scoped_views = false

  # Configure the default scope given to Warden. By default it's the first
  # devise role declared in your routes (usually :user).
  # config.default_scope = :user

  # Set this configuration to false if you want /users/sign_out to sign out
  # only the current scope. By default, Devise signs out all scopes.
  # config.sign_out_all_scopes = true

  # ==> Navigation configuration
  # Lists the formats that should be treated as navigational. Formats like
  # :html, should redirect to the sign in page when the user does not have
  # access, but formats like :xml or :json, should return 401.
  #
  # If you have any extra navigational formats, like :iphone or :mobile, you
  # should add them to the navigational formats lists.
  #
  # The "*/*" below is required to match Internet Explorer requests.
  # config.navigational_formats = ['*/*', :html]

  # The default HTTP method used to sign out a resource. Default is :delete.
  config.sign_out_via = :delete

  # ==> OmniAuth
  # Add a new OmniAuth provider. Check the wiki for more information on setting
  # up on your models and hooks.
  # config.omniauth :github, 'APP_ID', 'APP_SECRET', scope: 'user,public_repo'

  # ==> Warden configuration
  # If you want to use other strategies, that are not supported by Devise, or
  # change the failure app, you can configure them inside the config.warden block.
  #
  # config.warden do |manager|
  #   manager.intercept_401 = false
  #   manager.default_strategies(scope: :user).unshift :some_external_strategy
  # end

  # ==> Mountable engine configurations
  # When using Devise inside an engine, let's call it `MyEngine`, and this engine
  # is mountable, there are some extra configurations to be taken into account.
  # The following options are available, assuming the engine is mounted as:
  #
  #     mount MyEngine, at: '/my_engine'
  #
  # The router that invoked `devise_for`, in the example above, would be:
  # config.router_name = :my_engine
  #
  # When using OmniAuth, Devise cannot automatically set OmniAuth path,
  # so you need to do it manually. For the users scope, it would be:
  # config.omniauth_path_prefix = '/my_engine/users/auth'

  # ==> Turbolinks configuration
  # If your app is using Turbolinks, Turbolinks::Controller needs to be included to make redirection work correctly:
  #
  ActiveSupport.on_load(:devise_failure_app) do
    include Turbolinks::Controller
  end

  # ==> Configuration for :registerable

  # When set to false, does not sign a user in automatically after their password is
  # changed. Defaults to true, so a user is signed in automatically after changing a password.
  # config.sign_in_after_change_password = true
end

模型/user.rb如下:

class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  # devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable, :trackable, :confirmable

  devise :database_authenticatable, :registerable,
  :recoverable, :rememberable, :trackable, 
  :validatable, :confirmable#, authentication_keys: [:login]

  # Create relationship - User has many properties.
  has_and_belongs_to_many :properties
  has_many :portfolios, dependent: :destroy

  # attr_writer :login

  # def login
  #   # @login || self.username || self.email
  #   @login || self.email || self.encrypted_password
  # end

  # def contact_name
  #   "#{first_name} #{last_name}"
  # end

  # def company_name
  #   "AGENT"
  # end

end

下面的控制器/application_controller.rb:

class ApplicationController < ActionController::Base

    # Store last page for redirecting to last page on log in or log out.
    before_action :store_user_location!, if: :storable_location?

    protect_from_forgery prepend: true
    
    # To enable sign in to function correctly.
    skip_before_action :verify_authenticity_token, :only => :create

    before_action :configure_permitted_parameters, if: :devise_controller?

    def index
        
    end

    protected

    # Restrict parameters for sign up input.
    def configure_permitted_parameters
        added_attrs = [:first_name, :last_name, :email, :encrypted_password, :password_confirmation, :remember_me]
        devise_parameter_sanitizer.permit(:sign_up, keys: added_attrs)
        devise_parameter_sanitizer.permit(:account_update, keys: added_attrs)
        devise_parameter_sanitizer.permit(:sign_in, keys: added_attrs)
    end

    private
    
    def storable_location?
        request.get? && is_navigational_format? && !devise_controller? && !request.xhr? 
    end

    def store_user_location!
        # :user is the scope we are authenticating
        store_location_for(:user, request.fullpath)
    end

end

控制器/用户/sessions_controller.rb如下:

# frozen_string_literal: true

class Users::SessionsController < Devise::SessionsController
  # before_action :configure_sign_in_params, only: [:create]

  # GET /resource/sign_in
  # def new
  #   super
  # end

  # POST /resource/sign_in
  # def create
  #   super
  # end

  # DELETE /users/sign_out
  # def destroy
  #   super
  # end

  def after_sign_in_path_for(resource_or_scope)
    stored_location_for(resource_or_scope) || super
  end

  # protected

  # If you have extra params to permit, append them to the sanitizer.
  # def configure_sign_in_params
  #   devise_parameter_sanitizer.permit(:sign_in, keys: [:attribute])
  # end
end

下面的views/devise/session/new.html.erb:

<section class="form-auth text-center">
  <%= form_for(resource, as: resource_name, url: session_path(resource_name)) do |f| %>
    <!-- <img class="mb-4" src="" alt="" width="72" height="72"> -->
    <h1 class="h3 mb-3 font-weight-normal">Please Log In</h1>

    <label for="inputEmail" class="sr-only">Email address</label>
    <%= f.email_field :email, autofocus: true, class: "form-control", id: "inputEmail", placeholder: "Email address", autocomplete: "current-email", required: "" %>

    <label for="inputPassword" class="sr-only">Password</label>
    <%= f.password_field :password, autocomplete: "current-password", placeholder: "Password", class: "form-control", id: "inputPassword", required: "" %>
    
    <div class="checkbox mb-3">
      <label>
        <input type="checkbox" value="remember-me"> Remember me
      </label>
    </div>
    
    <button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
    <p class="mt-5 mb-3 text-muted">&copy; 2020</p>

  <% end %>

  <%= render "devise/shared/links" %>

</section>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Devise 和 Ruby on Rails:尝试登录时如何解决“Completed 401 Unauthorized”问题 的相关文章

  • 防止语言环境文件中的 HTML 字符实体被 Rails3 xss 保护破坏

    我们正在构建一个应用程序 这是我们第一个使用 Rails 3 的应用程序 并且我们必须从一开始就构建 I18n 作为完美主义者 我们希望在我们的视图中使用真正的排版 破折号 卷曲引号 省略号等 这意味着在我们的 locales xx yml
  • RubyMine 不能使用 Guard 吗?

    由于某些无法解释的原因 RubyMine 会自动保存您所做的每一个更改 因此每次击键都会触发 Guard 运行您的测试 最可笑的是 显然没有办法禁用这个自动保存 功能 我只是想知道 RubyMine 似乎是 Rails 开发人员中非常流行的
  • 使用 SASS 切换用户主题 - Ruby on Rails

    所以我有一个 Rails 管理系统 允许用户选择一个主题 基本上是一组 SASS 颜色变量 它将使用新颜色重新编译 application css scss 当用户从下拉菜单中选择并提交时 更改此设置的最佳方法是什么 我阅读了一些有关缓存和
  • 使用操作系统用户名/密码在 PHP 中进行身份验证?

    我想知道是否有一种方法可以使用 PHP 或者可能是其他一些 CGI 但最好是 PHP 来使用其操作系统 在本例中为 Linux Debian 5 用户名和密码来验证用户 可能的 难的 谢谢 一般来说 这种东西是特定于操作系统的 并与现有的身
  • 如何在 Ruby 中将“Access-Control-Allow-Origin”标头添加到 API 响应

    我正在面试前端开发人员的工作 并接受了构建简单前端界面的编码测试 我已经得到了服务器 它是用 Ruby 2 1 3 编写的 有 3 个端点 我将在前端客户端中使用它们 我对 Ruby 没有任何经验 但我按照他们的说明设置服务器 它似乎有效
  • 使用 Ruby on Rails 进行设计 - 强制用户在首次登录时更改密码

    我有一个运行 Devise 的 RoR 应用程序 Rails 4 2 Ruby 2 2 0 我已经进行了设置 以便管理员用户 标识了我添加到用户模型中的 is admin 布尔值 能够创建新的用户帐户 为他们提供生成的密码和确认电子邮件 这
  • 什么是“太聪明”的 Ruby 代码示例? [关闭]

    Closed 这个问题需要多问focused help closed questions 目前不接受答案 我正在与一些程序员朋友进行讨论 他们说他们看到 Ruby 程序员 尤其是 编写了很多 太聪明 的代码 所以我想知道那会是什么样子 我指
  • 如何在 Asp.Net MVC 上实现客户端 Ajax 登录(Asp.Net Webforms 解决方案的链接位于此处)

    我正在尝试在 Asp Net MVC 上实现客户端 ajax 登录 我以前在 WebForms 上设置得很好 但现在我已经转向 MVC 这给我带来了一些麻烦 如果您想要有关 Asp Net Webforms 的客户端 Ajax 登录的教程
  • IdentityServer4 客户端 - 刷新 CookieAuthenticationEvents 上的访问令牌

    我试图在访问令牌过期时使用刷新令牌 类似的问题已回答here https stackoverflow com a 41557598 3501052 And 更新令牌的示例代码 https stackoverflow com question
  • GitHub API:标记提交所属(与 git describe --tag 并行)

    我正在使用 GitHub API 进行实验octokit https github com octokit octokit rb红宝石 我的目标是能够提取提交 SHA 所属的 标签 现在我可以使用命令行轻松地执行此操作 gt git des
  • 强参数不起作用

    使用 Ruby 1 9 3 Rails 3 2 13 Strong parameters 0 2 1 我遵循了教程和railscasts中的每一个指示 但我无法让strong parameters工作 这应该是非常简单的事情 但我看不出错误
  • 如何从模型调用辅助方法?

    我使用 MongoDB 作为我的 Rails 应用程序中的数据库和 MongoID gem 我想从模型中调用辅助方法after create回调方法 这怎么可能 我的模型代码是 class Department include Applic
  • Mongoid 命名范围比较同一文档中的两个时间字段

    我需要在 Mongoid 中创建一个命名范围来比较同一文档中的两个时间字段 例如 scope foo where gt updated at gt gt checked at 这显然不会像它对待的那样起作用 checked at作为一个符号
  • Ruby on Rails 中的三重连接

    我对 Ruby on Rails 中的关联有疑问 应用程序中有项目 用户 角色和组 项目属于一个有用户的组 一个用户可以属于多个不同的组 但只能在该组中拥有一个特定的角色 例如 在一个组中 用户是项目所有者 但在另一个组中 他是作家 使用
  • rvm编译安装ruby 2.5.0出错

    我正在尝试使用 rvm 安装 ruby 2 5 0 但出现错误 我在 Ubuntu 18 16 和现在的 Linux Mint Cinnamon 上尝试过 基本上我在运行安装 ruby 的代码之前所做的是 打开 GPG 密钥https rv
  • 在 Rails 6 上定义 Secret_key_base 的正确方法是什么?

    正确的定义方式是什么secret key base既然我们已经有了每个环境的凭据 就可以在 Rails 6 上使用了吗 我的环境有变量SECRET KEY BASE但 Rails 并没有接受它 我尝试定义secret key base in
  • Ruby 未绑定方法:是否可以强制绑定到其他类的实例?

    我想知道我是否可以强迫这种情况发生 class A def bomb bomb end end class B end bomb A instance method bomb b B new bomb bind b 目前它抛出错误 Type
  • Firebase Auth - 最近登录多长时间

    我有一个个人资料选项卡 用户可以在其中按编辑并编辑他们的个人资料 我只想在必要时才需要他们的密码 所以想知道用户登录的时间是多少毫秒 这使得它不是最近登录 其中firebase会抛出错误 auth requires recent login
  • ApplicationController 的未定义方法“helper_method”,Rails 5

    我正在尝试使用doorkeeper 将oAuth2 0 集成到我的仅rails api 应用程序中 但我不断收到此错误 ApplicationController 的未定义方法 helper method 但无法找到解决该问题的明确解决方案
  • Rails 中的 PDF 导出

    我需要将包含一些图表的 HTML 页面导出为 PDF 有哪些好的 gem 可以做到这一点 PDFKit http railscasts com episodes 220 pdfkit http railscasts com episodes

随机推荐

  • Twitter Bootstrap 2 模式表单对话框

    我有以下对话框 div class modal div class modal header a class close a h3 Add Tags h3 div div class modal body div div
  • M1 MacBook Pro 和 cmake 的编译错误

    我刚刚拿到了新的 M1 MacBook Pro 正在尝试编译大学工作所需的代码库 以下是我已采取的步骤 我使用 Rosetta 将终端设置为始终打开 安装的自制程序using bin bash c curl fsSL https raw g
  • 通过 StackExchange.Redis 连接到 Redis Servier

    我尝试使用以下方法制作一个测试项目Redis https redis io服务器 通过 Virtual Box 安装在 Linux Ubuntu 虚拟机上 Linux 机器通过 Virtual Box 的桥接适配器与本地网络连接 Virtu
  • Mac OS Snow Leopard 上的两个版本的 PHP 以及使用 PECL 安装 xdebug

    我正在使用MAMP在我阅读一些有关内置 Apache PHP 的文章之前 我已经在 PHP 开发 标准 中使用过一段时间了雪豹 我决定转向那些我提供的但似乎有很多问题的人 第一件事是当我使用MAMP时 我将PEAR从1 9 0升级到1 9
  • 使用 gradle kotlin dsl 执行 JavaExec 任务

    我创建了简单的build gradle kts file group com lapots breed version 1 0 SNAPSHOT plugins java java sourceCompatibility JavaVersi
  • 跨页面加载跟踪子窗口

    如果重新加载父页面 是否可以跟踪子窗口 我目前打开窗口如下 var childWindow childWindow window open url 当我想重新打开同一个子窗口时 childWindow focus 明显的问题是 如果刷新父窗
  • Discord JS - DiscordAPIError:缺少访问权限

    所以我按照磨损钥匙教程来不和谐机器人 我不知道问题是什么 这是错误 home container node modules discord js src rest RequestHandler js 349 throw new Discor
  • cron 作业或 PHP 调度程序

    我使用 MYSQL 作为我的数据库 PHP 作为我的编程语言 我想运行一个 cron 作业 该作业将运行直到当前系统日期与我的数据库表中名为 PROJECT 的 截止日期 日期 列匹配 一旦日期相同的是 必须运行更新查询 这会将状态 项目表
  • Linux 中如何确定哪个进程正在使用某个端口

    我目前正在其默认端口上运行 RethinkDB 因为如果我将浏览器指向localhost 8080我看到 RethinkDB Web 界面 我想关闭 RethinkDB 并使用以下命令在另一个端口上重新打开它 port offset争论 然
  • 特定模型的自定义 REST url

    Ember 有没有办法为特定模型配置自定义 REST url 就像这个模型一样 App Post DS Model extend title DS attr string comments DS hasMany App Comment Ap
  • SQL原型设计:面对使用varchar(N)静默截断数据——有更好的选择吗? (天数据)

    情况 varchar 20 好像默默地截断在 Teradata 和not当遇到长度超过 20 个字符的字符串时扩展或抱怨 这有点令人惊讶 因为我预计列会自动扩展以适应更大的字符串 例如 30 个字符 或者如果更大的字符串会抛出错误遇到字符串
  • 在 Angular 中强制进行摘要

    在用户操作后的某个时刻 我希望发生摘要 因此 UI 反映了支持它的数据模型的更改 我有一个服务在回调中执行一些更改 异步 我明白那个 scope仅在控制器的上下文中才有意义 我可以通过执行来达到相同的效果吗 apply on the roo
  • 如何在 Cypress 的 E2E 测试中登录 Auth0?

    我已经开始测试 React Web 应用程序 但我没有走得太远 因为我遇到了登录问题 我在用cypress https www cypress io e2e测试工具 将显示一个带有登录按钮的欢迎页面 该页面会将您重定向到auth0 http
  • Traefikv2.3 出现 `Failed to list *v1beta1.IngressClass: ingressclasses.networking.k8s.io` 错误

    我正在尝试使用Traefik Kubernetes Ingress 我在用着traefik v2 3 K8的cli版本是v1 18 3服务器版本是v1 18 6IKS 我正在使用 IBM Kubernetes 服务来部署它 但我在 pod
  • 将 SSL 与 MAMP PRO 4 结合使用

    由于我已更新到 chrome 63 我在 localhost 中的网站被重定向到 https 因此我决定将 SSL 与 MAMP PRO 一起使用 但我无法使其工作 chrome 说您的连接不是私有的 在 MAMP 的 SSL 面板中 我生
  • 在 Three.js 中获取 Object3D 的大小

    我的场景中有这个 3D 对象 var icon new THREE Object3D var iconTexture THREE ImageUtils loadTexture images icon png iconMaterial new
  • Next.js API 路由神秘地修改 JSON 负载

    由于某种原因 当我通过 Postman 作为原始文本发送 JSON 格式的数据时 没有任何问题 当我通过 Postman 发送与原始 JSON 完全相同的数据时 区别应该只是content type标头是application json代替
  • 抑制 retina.js 库中的 404 错误

    我们使用js库视网膜 js https github com imulus retinajs 它将低质量图像替换为 视网膜 图像 大小乘以 2 问题是 retina js 会为每个无法找到的 视网膜 图像抛出 404 错误 我们拥有一个网站
  • Github 下载文件夹为 zip

    如何为我的 Github 存储库的访问者提供一个链接 以将我的存储库的 builds 文件夹下载为 zip 文件 该文件夹包含应用程序所需的可执行文件 着色器和纹理 当然 我可以手动构建该目录的 zip 文件并将其添加到存储库中 但这会导致
  • Devise 和 Ruby on Rails:尝试登录时如何解决“Completed 401 Unauthorized”问题

    我正在尝试将 Devise gem v4 7 2 与 Ruby on Rails v6 0 3 2 一起使用 单击 登录 按钮时 我收到以下输出 Started POST users sign in for 1 at 2020 11 21