我有一个使用 rails 构建的简单网络应用程序,使用 devise 进行用户登录。目前,用户可以注册、登录和注销,并在登录后发布新帖子。 最终我计划通过移动应用程序使这个 api 可用,我理解这个过程的第一步是使用 CURL 命令登录。我遇到了一些问题。
这是 CURL 命令:
curl -H 'Content-Type: application/json' -X POST http://localhost:3000/users/sign_in -d '{"user": {"email":"test@test. com", "密码": "密码"}}' -c cookie
Controller 代码如下:
class Api::PostsController < ApplicationController
skip_before_action :verify_authenticity_token
before_action :authenticate_user!
# protect_from_forgery with: :null_session
def index
render json: Post.all
end
def show
post = Post.find(params[:id])
render json: post
end
def create
post = Post.new(post_params)
if post.save
render status: 200, json: {
message: "Successfully created post",
post: post
}.to_json
else
render status: 422, json: {
errors: post.errors
}.to_json
end
end
def destroy
post = Post.find(params[:id])
post.destroy
render status: 200, json: {
message: 'Successfully deleted post'
}.to_json
end
private
def post_params
params.require("post").permit("city", "country", "image", "lon", "lat")
end
end
这是我从服务器收到的错误:
Processing by Devise::SessionsController#create as */*
Parameters: {"user"=>{"email"=>"test@test.com", "password"=>"[FILTERED]"}, "session"=>{"user"=>{"email"=>"test@test.com", "password"=>"[FILTERED]"}}}
Can't verify CSRF token authenticity
Completed 422 Unprocessable Entity in 20ms (ActiveRecord: 0.0ms)
如您所见,我包含了 skip_before_action :verify_authenticity_token
代码以跳过 CSRF token 检查,但是此检查似乎发生在 SessionsController
中。
我需要在别处添加这行代码吗?我对 Rails/Devise 还是个新手,所以请原谅我的知识不足。
最佳答案
Devise 是一个 Rails 引擎,因此它有自己的一组 Controller ,这些 Controller 不继承自 ApplicationController
。要使覆盖工作,您需要在您的应用程序中创建继承自设计 Controller 的 Controller ,然后告诉 Devise 使用这些 Controller 而不是默认 Controller 。 This Devise wiki 上的操作方法可能会有所帮助。
话虽如此,CSRF 保护是有原因的,如果禁用它,通过网络浏览器登录的用户将不再受到保护,这是一个非常糟糕的主意。一个更好的方法是有一个适当的机制来通过与 Web GUI 不同的 API 登录。有一个 :token_authenticatable
在这里提供帮助的模块,以及使用它的良好指南 here .
但是...制作 Devise 的 Platformatec 人员已经从核心中删除了 :token_authenticatable
,因为他们说它不是 100% 安全的(参见 this blog post)。有一个很好的 Stackoverflow 问题 here解释问题并提出一些更好的实现方法。
希望这对事情有所启发。
关于ruby-on-rails - 使用 curl 命令通过 devise 登录到 rails api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30373396/