首页 > 解决方案 > 将设计与 Rails 一起使用并将 authentication_keys 设置为 [:username] 时出现 401 Auth 错误

问题描述

嗨,我在这里遇到了类似的错误,但我认为根本原因是不同的,因为我发现没有任何解决方案有效。基本上我在一个小项目上使用 Rails 中的 Devise,虽然使用 sign_up 页面工作得很好(用户被放置到数据库中),但 sign_in 页面似乎找到了用户,但没有将它们设置为当前用户。我从开箱即用的解决方案中唯一改变的是使用 :username 作为身份验证密钥而不是 :email。

class ApplicationController < ActionController::Base
  protect_from_forgery prepend: true

  skip_before_action :verify_authenticity_token
  before_action :configure_permitted_parameters, if: :devise_controller?

  protected

  def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:sign_up) { |u| u.permit(:username, :email, :password, :password_confirmation) }
    devise_parameter_sanitizer.permit(:sign_in) { |u| u.permit(:username, :password, :remember_me) }

    devise_parameter_sanitizer.permit(:account_update) { |u| u.permit(:username, :email, :password, :current_password) }
  end
end

在我的初始化程序/devise.rb 中:

  config.authentication_keys = [:username]
  config.case_insensitive_keys = [:username]
  config.strip_whitespace_keys = [:username]

用户模型

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

  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable

  def email_required?
    false
  end

  def email_changed?
    false
  end

  def will_save_change_to_email?
    false
  end
end

控制台的输出如下所示:

Started POST "/users/sign_in" for ::1 at 2020-08-11 17:12:53 +0100
Processing by Devise::SessionsController#create as HTML
  Parameters: {"authenticity_token"=>"EbXx8CI0+FsF1HkNwHqsUW09BJ0HOW2lJDjWmJEc03d0AeaBOWVxNFpupUA+qLKIsiVMZ9kfbmCZidZMZIKoXA==", "user"=>{"username"=>"bob", "password"=>"[FILTERED]", "remember_me"=>"0"}, "commit"=>"Log in"}
  User Load (0.4ms)  SELECT "users".* FROM "users" WHERE "users"."username" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["username", "bob"], ["LIMIT", 1]]
Redirected to http://localhost:3031/
Completed 302 Found in 103ms (ActiveRecord: 0.4ms | Allocations: 3788)


Started GET "/" for ::1 at 2020-08-11 17:12:53 +0100
Processing by BoardsController#index as HTML
Completed 401 Unauthorized in 0ms (ActiveRecord: 0.0ms | Allocations: 248)

Boards 控制器只有:

before_action :authenticate_user!

由于身份验证失败,因此重定向回 sign_in。

感谢您的任何建议!

标签: ruby-on-railsrubyauthenticationdevise

解决方案


把它放在这里以防其他人遇到这个问题。

如果您使用的是 Stimulus Reflex,它当前会禁用 rails cookie_store 并改用 cache_store。您可以切换回来:

config.session_store :cache_store

回到 Rails 默认

config.session_store :cookie_store

或运行rails dev:cache以在您的开发环境中启用 cache_store。


推荐阅读