我已经设置了一个新的rails api应用程序并尝试使用devise进行登录,但即使使用正确的电子邮件和密码,总是会收到401
尝试解决了几天但没有成功
详情如下
Rails 7.1.3.2
devise (4.9.4)
config/routes.rb
Rails.application.routes.draw do
devise_for :users, path: '', path_names: {
sign_in: 'login',
sign_out: 'logout',
registration: 'signup'
},
controllers: {
sessions: 'users/sessions',
registrations: 'users/registrations'
}
get "up" => "rails/health#show", as: :rails_health_check
namespace :api do
namespace :v1 do
resources :users
end
end
end
app/controllers/users/sessions_controller.rb
class Users::SessionsController < Devise::SessionsController
respond_to :json
end
app/models/user.rb
class User < ApplicationRecord
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
end
邮箱和密码正确,可以在DB中找到。 即使是邮差,我也收到 401
邮差
POST: localhost:3000/login
Body: {
"email": "[email protected]",
"password": "123456"
}
---------------------------
response
You need to sign in or sign up before continuing.
Rails 服务器日志
Started POST "/login" for ::1 at 2024-05-08 18:42:36 +0530
ActiveRecord::SchemaMigration Load (0.1ms) SELECT "schema_migrations"."version" FROM "schema_migrations" ORDER BY "schema_migrations"."version" ASC
Processing by Users::SessionsController#create as */*
Parameters: {"email"=>"[email protected]", "password"=>"[FILTERED]", "session"=>{"email"=>"[email protected]", "password"=>"[FILTERED]"}}
Completed 401 Unauthorized in 4ms (ActiveRecord: 0.0ms | Allocations: 2586)
schema.rb
ActiveRecord::Schema[7.1].define(version: 2024_04_28_060440) do
create_table "users", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["email"], name: "index_users_on_email", unique: true
t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
end
end
以下建议将不起作用,因为我创建了仅 api 应用程序(不会有任何视图)
<p class="notice"><%= notice %></p>
<p class="alert"><%= alert %></p>
通过rails控制台添加用户
u = User.new(email: '[email protected]')
u.password = '123456'
u.password_confirmation = '123456'
u.save!
找出问题所在。
请求正文应包含用户对象,例如
{ "user":
{
"email": "[email protected]",
"password": "123456"
}
}
简单的错误。
感谢您尝试解决问题。