[英]Rails: Unable to sign_in a user using Devise
我使用Devise gem在rails中创建了一个演示验证应用程序。 我创建了一个会话控制器来登录用户。 但是当我使用邮递员向会话控制器发送请求localhost:3000/api/v1/sessions/
,出现以下错误:
"Could not find a valid mapping for #<User id: 2, email: "smith@railsapi.com", encrypted_password: "$2a$10$J5lCfQzWsxvjsXe.3EXfZ.ST9nztLLW8fhqYgXNtJP1...", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 0, current_sign_in_at: nil, last_sign_in_at: nil, current_sign_in_ip: nil, last_sign_in_ip: nil, created_at: "2016-03-26 03:59:22", updated_at: "2016-03-26 03:59:22", auth_token: "_D3GU1TftgP7YHNcRftN">"
这是我的模型users.rb
class User < ActiveRecord::Base
before_create :generate_authentication_token!
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
validates :auth_token, uniqueness: true
def generate_authentication_token!
begin
self.auth_token = Devise.friendly_token
end while self.class.exists?(auth_token: auth_token)
end
end
这是我的会话控制器
class Api::V1::SessionsController < ApplicationController
def create
user_password = params[:session][:password]
user_email = params[:session][:email]
puts user_password
puts user_email
user = user_email.present? && User.find_by(email: user_email)
if user.valid_password? user_password
sign_in user, store: false
user.generate_authentication_token!
user.save
render json: user, status: 200
else
render json: { errors: "Invalid email or password" }, status: 422
end
end
end
和我的routes.rb文件:
Rails.application.routes.draw do
# API routes path
namespace :api, defaults: { format: :json } do
namespace :v1 do
resources :users, only: [:show, :create, :update]
resources :sessions, only:[:create, :destroy]
end
end
end
application.rb中
require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module DemoApi
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
# Do not swallow errors in after_commit/after_rollback callbacks.
config.active_record.raise_in_transactional_callbacks = true
DeviseController.respond_to :html, :json
end
end
如果有人能告诉我哪里出错了,我真的很感激。 谢谢
解决此问题的一种更好,更简单的方法是使用devise_token_auth gem 设计来完成JWT(JSON Web Token)身份验证系统。 这个宝石将为您提供创建JWS系统所需的所有工具。 我们在我的小镇上谈论了API身份验证,我使用此功能创建了一个基本应用程序。 我将在这里描述我如何实现解决方案,但是可以在这里查看样本回购 。 它是一个类似Instagram的应用程序。
第1步: 添加到您的Gemfile:
gem 'devise_token_auth'
安装宝石
$ bundle install
第2步 : 生成gem所需的配置
$ rails generate devise_token_auth:install User auth
$ bundle exec rake db:migrate
它将生成一个迁移文件,为您的用户模型添加几个新属性,但基本上主线是:
## Tokens
t.text :tokens
它将提供一系列令牌,这些令牌将保留在数据库中以供用户认证
它还添加了用于验证/ sign_in / sign_up的路由
mount_devise_token_auth_for "User", at: 'auth'
步骤3:寻找路线
现在,在您的终端上执行:
$ rake routes
它将显示用于认证 , 登录和sign_up的路由
步骤4:使用邮递员试用
正如您所提到的,使用邮递员,您现在可以向localhost:3000 / auth /发送POST ,其中包含电子邮件 , 密码和password_confirmation (需要这些字段)来注册用户。 (检查devise_token_auth自述文件以了解如何sign_in和sign_out )。
这里的关键是注册请求和sign_in请求将返回包含许多标题的响应(如果状态代码为OK),其中包含您需要的所有身份验证信息。 您必须在移动客户端上提取这些标头(甚至使用邮递员来测试所需的身份验证路由),并添加到您的应用中需要身份验证的所有其他请求。
尝试这样做,克隆并检查我指出的Sample Repo ,看看你是否完成了它。 如果你知道的话,请告诉我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.