5
我正在尝试使用Devise和authenticatable_token构建API以登录到我的Rails应用程序。 我在API模块创建一个SessionsController写下了下面的代码sign_in:用Devise和token_authenticatable登录Rails应用程序:“401未经授权”
module Api
module V1
class SessionsController < Devise::SessionsController
def create
resource = warden.authenticate!(scope: resource_name, recall: "#{controller_path}#new")
sign_in(resource_name, resource)
if current_user
if !current_user.authentication_token
current_user.reset_authentication_token!
end
render json: {success: true, auth_token: resource.authentication_token, email: resource.email}
else
invalid_login_attempt
end
end
protected
def invalid_login_attempt
warden.custom_failure!
render json: {success: false, message: "Error with your login or password"}, status: 401
end
end
end
end
的问题是,应用程序提出了401,当我使用的登录,没有任何标记。
RestClient.post "http://localhost:3000/api/v1/users/sign_in", {user: {email: "[email protected]", password: "FILTERED"}}.to_json, :content_type => :json, :accept => :json
但如果我设置由报名方式它的工作原理提供的令牌:
response_json = RestClient.post "http://localhost:3000/api/v1/users/sign_in?auth_token=#{@token}", {user: {email: "[email protected]", password: "FILTERED"}}.to_json, :content_type => :json, :accept => :json
那么,为什么呢?执行登录时是否可以禁用令牌认证过程?
感谢您的回答。我遵循你网站上的指示,但我仍然得到一个401.此外,我得到了一个错误'未定义的方法'拆分'的500:失败:'resource = warden.authenticate!(:scope => resource_name, :召回=>:失败)'。我也删除了内容类型并接受了我的请求中的指令并添加了navigational_formats。 – obo
其实它是'warden.authenticate!',提高了401. – obo
我终于成功了。我的错误是由错误的路线引起的。我不得不使用localhost:3000/api/v1/sign_in而不是api/v1/users/sign_in。顺便说一句,你的链接和你的建议在配置中帮助我使事情正常工作。 – obo