繁体   English   中英

使用curl进行Rails API登录

[英]Rails API login using curl

我正在使用身份验证构建Rails API,并尝试使用curl测试登录。 我希望最终能够使用移动应用程序登录并检索身份验证令牌。 我目前有

# api/sessions_controller.rb
class Api::SessionsController < Api::BaseController
   skip_before_filter  :verify_authenticity_token

   def create
   @user = User.find_for_authentication(email: params[:email])

   if @user && @user.valid_password?(params[:password])
      @user.generate_authentication_token

         render :json=> {:user_id=>@user.id, :token=>@user.authentication_token}
      else
         error! :unauthenticated
      end
   end

   private

   def user_params
      params.require(:user).permit(:email, :password)
   end
end

我做一个curl -i -X POST -d "user[email]=user@user.com&user[password]=password" "http://localhost:3000/api/sessions"

但登录失败

HTTP/1.1 401 Unauthorized
X-Frame-Options: SAMEORIGIN
X-Xss-Protection: 1; mode=block
X-Content-Type-Options: nosniff
Content-Type: application/json; charset=utf-8
Cache-Control: no-cache
X-Request-Id: 5d84cbb4-28d3-48fb-bfce-a29d0f40569d
X-Runtime: 0.029000
Server: WEBrick/1.3.1 (Ruby/2.1.5/2014-11-13)
Date: Mon, 02 Mar 2015 02:29:32 GMT
Content-Length: 61
Connection: Keep-Alive
Set-Cookie: request_method=POST; path=/

{"error":"You need to sign in or sign up before continuing."}

如果您有任何建议,请告诉我。 谢谢!

将代码更改为以下内容。 您的代码引用了错误的参数。

   @user = User.find_for_authentication(email: params[:user][:email])

   if @user && @user.valid_password?(params[:user][:password])
      @user.generate_authentication_token

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM