You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rails 7.2.1集成Devise基础认证时遭遇401 Unauthorized错误

问题描述

我安装了Rails 7.2.1并配置了基础版Devise,在ApplicationController中设置了如下跳转方法:

def after_sign_in_path_for(current_user)
  # Assuming 'Dashboard' is a model and you have a show action
  dashboard_path(current_user)
end

def after_sign_up_path_for(current_user)
  # Assuming 'Dashboard' is a model and you have a show action
  dashboard_path(current_user)
end 

确认登录凭据有效,但尝试登录时持续出现401 Unauthorized错误,相关日志如下:

App 8384 output: I, [2024-09-20T22:12:03.793655 #8384]  INFO -- : [58b545d7-4177-4864-8459-3ddd062477a7] Started POST "/users/sign_in" for 173.171.196.191 at 2024-09-20 22:12:03 +0000
App 8384 output: I, [2024-09-20T22:12:03.794580 #8384]  INFO -- : [58b545d7-4177-4864-8459-3ddd062477a7] Processing by Users::SessionsController#create as TURBO_STREAM
App 8384 output: I, [2024-09-20T22:12:03.794622 #8384]  INFO -- : [58b545d7-4177-4864-8459-3ddd062477a7]   Parameters: {"email"=>"mhenry1228@gmail.com", "password"=>"[FILTERED]", "remember_me"=>"0", "commit"=>"Log in"}
App 8384 output: I, [2024-09-20T22:12:03.795139 #8384]  INFO -- : [58b545d7-4177-4864-8459-3ddd062477a7] CSRF Protection Enabled? false
App 8384 output: I, [2024-09-20T22:12:03.795444 #8384]  INFO -- : [58b545d7-4177-4864-8459-3ddd062477a7] Completed 401 Unauthorized in 1ms (ActiveRecord: 0.0ms (0 queries, 0 cached) | GC: 0.0ms)
App 8384 output: I, [2024-09-20T22:12:03.796212 #8384]  INFO -- : [58b545d7-4177-4864-8459-3ddd062477a7] Processing by Users::SessionsController#new as TURBO_STREAM
App 8384 output: I, [2024-09-20T22:12:03.796252 #8384]  INFO -- : [58b545d7-4177-4864-8459-3ddd062477a7]   Parameters: {"email"=>"mhenry1228@gmail.com", "password"=>"[FILTERED]", "remember_me"=>"0", "commit"=>"Log in"}
App 8384 output: I, [2024-09-20T22:12:03.796357 #8384]  INFO -- : [58b545d7-4177-4864-8459-3ddd062477a7] CSRF Protection Enabled? false
App 8384 output: I, [2024-09-20T22:12:03.798636 #8384]  INFO -- : [58b545d7-4177-4864-8459-3ddd062477a7]   Rendered layout layouts/application.html.erb (Duration: 1.5ms | GC: 0.1ms)
App 8384 output: I, [2024-09-20T22:12:03.798781 #8384]  INFO -- : [58b545d7-4177-4864-8459-3ddd062477a7] Completed 200 OK in 2ms (Views: 1.9ms | ActiveRecord: 0.0ms (0 queries, 0 cached) | GC: 0.1ms)

日志显示CSRF保护未启用,请求处理后返回401错误,随后重新渲染登录页面返回200,不清楚错误原因,寻求解决办法。

解决办法

1. 修复CSRF保护配置

日志明确显示CSRF Protection Enabled? false,这是核心问题:

  • 检查config/application.rb,确保包含启用CSRF的配置:
    config.action_controller.default_protect_from_forgery = true
    
  • 检查ApplicationController,移除任何错误禁用CSRF的代码,比如skip_before_action :verify_authenticity_token(除非有明确豁免需求)。

2. 确保表单包含CSRF令牌

Devise默认会生成CSRF令牌,但自定义视图或布局可能遗漏:

  • 在布局文件layouts/application.html.erb中确认存在<%= csrf_meta_tags %>,Turbo依赖这个处理表单提交;
  • 如果是自定义登录视图,在表单内添加<%= form_authenticity_token %>。

3. 处理Turbo兼容性问题

日志显示请求为TURBO_STREAM,Rails 7默认启用Turbo,可能导致登录流程异常:

  • 临时在登录表单中添加data-turbo="false"禁用Turbo提交:
    <%= form_for(resource, as: resource_name, url: session_path(resource_name), data: { turbo: false }) do |f| %>
      <!-- 表单内容 -->
    <% end %>
    
  • 或者自定义SessionsController控制响应格式:
    创建app/controllers/users/sessions_controller.rb:
    class Users::SessionsController < Devise::SessionsController
      respond_to :html
    
      def create
        super do |resource|
          redirect_to after_sign_in_path_for(resource) && return if resource.persisted?
        end
      end
    end
    

4. 验证Devise基础配置

  • 检查config/initializers/devise.rb,确保config.http_authenticatable未被设置为true(该配置会启用HTTP认证而非表单认证);
  • 确认用户模型(如User)包含必要的Devise模块:
    devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable
    

5. 检查路由有效性

  • 确认config/routes.rb中Devise路由配置正确:devise_for :users;
  • 验证dashboard_path路由存在且指向正确动作,比如:
    get '/dashboard/:id', to: 'dashboards#show', as: 'dashboard'
    

内容的提问来源于stack exchange,提问作者Havic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 05:35:55