我已经在使用Rails项目。现在,我试图基于react-native为移动版本创建API。我现在遇到的问题是如何实现API身份验证。我的项目(网络版本)使用Devise gem进行身份验证。
据我了解,对于身份验证,我需要使用令牌。所以我已经安装了simple_token_authentication gem。在不同的教程中找到了一些说明,我需要为我的API覆盖devise的SessionsController和RegistrationsController控制器。因此,在文件夹controllers / api / v1内部,我用以下代码创建了SessionsController:
acts_as_token_authentication_handler_for User, fallback_to_devise: false
respond_to :json
skip_before_filter :authenticate_entity_from_token!, only: [:create]
skip_before_filter :authenticate_entity!, only: [:create]
# POST /users/sign_in
def create
self.resource = warden.authenticate!(auth_options)
sign_in(resource_name, resource)
reset_token resource
if current_user
render :json => {
:user => current_user,
:status => :ok,
:authentication_token => current_user.authentication_token
}
else
render :json => {
:status => :error
}
end
end
# DELETE /users/sign_out
def destroy
warden.authenticate!
reset_token current_user
end
private
def sign_in_params
params.fetch(:user).permit([:password, :email])
end
def reset_token(resource)
resource.authentication_token = nil
resource.save!
end
end
在我的路线中,我添加了以下代码:
namespace :v1 do
resources :properties
devise_for :users, :controllers => {registrations: "api/v1/registrations", sessions: "api/v1/sessions"}
end
end
但是,当我尝试发送有效的电子邮件和密码并且所有时间都遇到404错误时。我不确定应该在哪个网址上发送,所以我尝试了不同的方法,例如: http://localhost:3000/api/v1/sign_in或http://localhost:3000/api/v1/users或http://localhost:3000/api/v1/session,但没有任何效果。我认为控制器出现问题,或者我使用了错误的网址?