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”问题 的相关文章

  • Nokogiri 保持 HTML 实体不变

    我希望 Nokogiri 保持 HTML 实体不变 但它似乎正在将实体转换为实际的符号 例如 Nokogiri HTML fragment p reg p to s 结果是 p p 似乎没有什么可以将原始 HTML 返回给我 inner h
  • rvm gem 安装错误?

    我正在摆弄 ruby gems 和 rvm 它工作得很好 但现在当我尝试安装 gem 时出现错误 gem install Rails错误 同时 执行 gem Errno EACCES 权限被拒绝 Users da rvm gems ruby
  • 没有要加载的文件 - ffi_c (LoadError)

    这个问题困扰了我几天 每当我使用 bring to front 方法时 require rubygems require watir browser Watir Browser new browser bring to front 我收到此
  • Bundle 说 gem 丢失了 - 但事实并非如此?

    背景 我正在维护contentRuby On Rails 站点 但我确实没有 Rails 的经验 当尝试运行 Rails 服务器时 rails s我明白了 在任何来源中均找不到 activesupport 3 2 0 Run bundle
  • 用户未定义的方法 attr_accessible 错误

    我正在尝试创建某种登录 我创建了一个用户脚手架并将此代码放在我的 user rb 中 class User lt ActiveRecord Base attr accessible name password digest password
  • 如何使用 next auth 通过自定义 Spring API 库和端点进行身份验证

    我是 Next js 的新手 正在将我的前端从 React 迁移到 Next v4 我已经使用 Spring 开发了一个后端 它连接到 Azure 上托管的 MySQL 数据库 该 API 在 Postman 和 React 前端上经过全面
  • 如何为 ApplicationController 中 after_action 过滤器中的所有操作渲染 json?

    是否可以在 Rails ApplicationController 中创建一个 after filter 方法 该方法在每个操作上运行并呈现为 JSON 我正在构建一个 API 并且希望将控制器中的每个操作的输出呈现为 JSON 客户控制器
  • 将rails_admin 与rails_api 结合使用

    我最初将此发布为Rails api GitHub 上的问题 https github com sferik rails admin issues 2617 但由于不活跃 我现在将其发布在这里 我正在尝试使用rails admin使用 Rai
  • 无法启动活动?

    在添加异步任务之前 我对代码进行了一些更改 我的应用程序可以正常工作 从远程服务器验证用户名和密码 但在登录成功消息消失时无法启动其他活动 有人建议我添加异步任务 现在我已经添加了该任务 但是当我输入正确的用户名和密码时 它会停止工作 当我
  • Ruby 中的 DateTime.parse() 是否依赖于语言环境?

    我想知道以下示例的输出 解析时01 03 它会被解决为Mar 1st or Jan 3rd Ruby 不依赖于语言环境 因为红宝石是一个服务器端语言而不是客户端像 JavaScript 一样的语言 Ruby 使用系统时钟yourWeb 应用
  • 从父应用程序重新打开 Rails 3 引擎类

    就目前而言 您无法重新打开引擎中包含的引擎类 app只需在父应用程序的目录中添加相同的类即可 app目录 例如 my engine app controllers users controller rb my app app control
  • 什么是适合 Rails 3 的测试框架?

    去年我一直在使用 Ruby On Rails 但是 无法进行单元测试 现在我必须编写单元测试代码 哪个测试框架好 为什么 有这方面的好的教程吗 我的系统配置 Ruby 1 9 2 Rails 3 Ubuntu 10 第一个技巧是 尝试升级到
  • TortoiseSVN 不要求身份验证?

    我已经在conf文件中设置了一个新的SVN存储库 运行SVNServe anon access none SVNServe 忠实地正确地做到了这一点 但是当我尝试使用 TortoiseSVN 浏览存储库时 它只是说不允许访问 它不应该要求我
  • Ruby on Rails 服务器在 HTTPS POST 请求期间崩溃

    我正在尝试与你沟通城市飞艇API http urbanairship com docs push html broadcast使用 ROR Web 应用程序 在我的控制器中 我有以下代码 require net http require n
  • Ionic/Cordova 应用程序中的身份验证

    首先 我不是专业人士 在我成为一名更好的开发人员的过程中 我试图了解需要什么以及如何完成为 Ionic Framework 应用程序创建注册 登录 大多数单页应用程序 SPA 在节点服务器上处理身份验证 该服务器还为客户端提供 HTML 就
  • Heroku Rails 应用程序级别不记录日志

    我在 Heroku 上有一个 Rails 应用程序 它没有在应用程序级别进行日志记录 当前版本 红宝石1 9 3 导轨3 1 3 在 config environment development rb 中有以下几行 config logge
  • 正则表达式的 o 修饰符是什么意思?

    Ruby 正则表达式有一些选项 例如i x m o i例如 意味着忽略大小写 什么是o选项是什么意思 在ri Regexp 它说o意味着执行 仅插值一次 但是当我这样做时 a one b a a two b不改变 它保持 one 我缺少什么
  • 为 RoR 中的每个用户创建新的 URL 路径

    如何在 Ruby on Rails 中实时创建新的 URL 路径 例如 我希望我的用户拥有 name XXX com 或 XXX com name 仅供参考 我在 Heroku 上托管代码 看看 subdomain fu 插件 https
  • 通过 AJP 将 REMOTE_USER 转发到 tomcat(例如用于 shibboleth)

    今天我刚刚遇到了以下问题 1 我将apache配置为基本身份验证 需要有效用户 这有效 2 我进一步配置 apache 将某些路径 在我的例子中为 idp 的请求转发到 tomcat servlet shibboleth IDP 结果是 s
  • 将查询字符串参数作为表单发布的一部分发送

    有没有办法捕获查询字符串并将其作为表单帖子的一部分发送 我正在使用 Rails 2 3 5 我的用户所在的页面有多个查询字符串参数 在此页面上 他们将提交一份表格 在接收帖子的操作中 我想知道这些查询字符串参数是什么 显然 它们不是作为邮件

随机推荐

  • 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