我正在使用身份验证构建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."}
如果您有任何建议,请与我们联系。谢谢!
答案 0 :(得分:0)
将代码更改为以下内容。你的代码指的是错误的参数。
@user = User.find_for_authentication(email: params[:user][:email])
if @user && @user.valid_password?(params[:user][:password])
@user.generate_authentication_token