簡體   English   中英

將 devise 與 Rails 一起使用並將 authentication_keys 設置為 [:username] 時出現 401 Auth 錯誤

[英]401 Auth Error when using devise with Rails and setting authentication_keys to [:username]

嗨,我在這里遇到了類似的錯誤,但我認為根本原因是不同的,因為我發現沒有任何解決方案有效。 基本上我在 Rails 的一個小項目中使用 Devise,雖然使用 sign_up 頁面工作得很好(用戶被放入數據庫),但 sign_in 頁面似乎找到了用戶,但沒有將它們設置為當前用戶。 我從開箱即用的解決方案中唯一改變的是使用:用戶名作為身份驗證密鑰,而不是: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]

用戶 model

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

控制台的output如下圖所示:

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)

板子 Controller 簡單地具有:

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。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM