基于令牌的Rails JSON API身份validation

我在rails中制作API。 对于正常的身份validation,我们使用设计,但在API中如何实现设计validation。

gem 'devise_token_auth' 

有人更喜欢这个gem进行身份validation,但没有可用的教程。 如何在rails api中实现authenitication?

您可以做的最好的事情是遵循最有可能是最新的github教程 。

首先,您应该遵循TLDR部分。
请注意,前端开发人员需要了解使用规范 。
最后,您想要查看文档。 以下是一些可能有用的示例:

路线

 Rails.application.routes.draw do # Stuff devise_for :admin_users, ActiveAdmin::Devise.config ActiveAdmin.routes(self) devise_for :users root to: "home#index" # The API part namespace :api, defaults: {format: :json} do scope :v1 do mount_devise_token_auth_for 'User', at: 'auth', skip: [:omniauth_callbacks] resources :stuff, only: [:index, :show] end end end 

控制器

 module Api class StuffsController < ApiController before_action :authenticate_user! ... end end 

API控制器

 class ApiController < ApplicationController include DeviseTokenAuth::Concerns::SetUserByToken end 

用户模型

 class User < ActiveRecord::Base # Include default devise modules. devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable include DeviseTokenAuth::Concerns::User end 

最后不要忘记在相应的初始化程序中配置gem。

这是一个关于使用devise_token_auth进行API身份validation的好教程。 此外, devise_token_auth gem的github页面似乎有一个非常好的文档,可以帮助您入门。

如果您正在寻找一个理解相关概念的好教程,那么这里有一个彻底的演练,即使用基于令牌的身份validation创建Rails API(不使用devise_token_auth ,但有助于理解这些概念)。

我还建议你看一下JWT(JSON Web Token) ,它适用于大规模的Rails API。 这是另一个解释如何使用JWT构建Rails API的教程

您可以向表中添加属性“authentication_token”并使用此gem:

https://github.com/robertomiranda/has_secure_token

在application_controller中:

 def authenticate_user! authenticate_user_from_token! super end def authenticate_user_from_token! User.find_by_authentication_token(user_token) end def user_token request.headers['X-AUTH-TOKEN'].presence || params['auth_token'].presence end 

在我目前的项目中,我实现了simple_token_authentication 。 它也很容易实现和使用。

只需将以下内容添加到Gemfile中并运行bundle install

 gem 'simple_token_authentication', '1.12.0' 

其余所有步骤都在其文档中给出,并且非常容易遵循。