ruby-on-rails - 将设计与 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。
感谢您的任何建议!
解决方案
把它放在这里以防其他人遇到这个问题。
如果您使用的是 Stimulus Reflex,它当前会禁用 rails cookie_store 并改用 cache_store。您可以切换回来:
config.session_store :cache_store
回到 Rails 默认
config.session_store :cookie_store
或运行rails dev:cache
以在您的开发环境中启用 cache_store。
推荐阅读
- python - 图书推荐引擎 - IndexError:索引 1 超出轴 0 的范围,大小为 1
- docker - 变量无法访问或未保存在 Gitlab ci 作业中
- javascript - Document.createNodeIterator() - 防止无限迭代
- android - Android:为 Android 12 拉伸的 SplashScreen 图像
- css - CSS 颜色值突出显示
- c - 使用 c 在 putty 中仅采用一个命令行参数
- redis - Redis 主从配置
- python - Pandas 以主键列为索引重塑列
- python - Python如何识别函数中的变量是全局变量还是局部变量?
- python - 使用 Pydantic 和 FastAPI 验证递归数据的最佳方式