基于令牌的Rails JSON API认证 [英] Token based authentication for Rails JSON APIs
问题描述
gem'devise_token_auth'
有人喜欢这个gem用于身份验证,但没有可用的教程。
如何在rails api中实现认证?
最好的事情是遵循 github教程,最有可能是最新的。
首先,您应该遵循 TLDR 部分。
请注意,前端开发人员需要了解使用规范。
最后,您需要了解文档。以下是一些可能有帮助的样本:
路线
code> Rails.application.routes.draw do
#Stuff
devise_for:admin_users,ActiveAdmin :: Devise.config
ActiveAdmin.routes(self)
devise_for:users
root to:home#index
#API部分
命名空间:api,默认值:{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控制器
类ApiController< ApplicationController
包含DeviseTokenAuth :: Concerns :: SetUserByToken
end
用户模型
class User< ActiveRecord :: Base
#包含默认设计模块。
devise:database_authenticatable,:可注册,
:可恢复,可记忆,可追踪,可验证
包含DeviseTokenAuth :: Concerns :: User
end
最后不要忘记在相应的初始化程序中配置gem。
I make API in rails. For normal authentication we use devise but in API how to implement devise for authentication.
gem 'devise_token_auth'
Someone prefer this this gem for authentication but there are no tutorial available for that. How to implement authenitication in rails api?
The best thing you can do is to follow the github tutorials which are most likely to be up-to-date.
First you should follow the TLDR part.
Note that the frontend developpers need to know about the usage specification.
Finally you want to go through the documentation. Here are some samples that might help:
Routes
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
A controller:
module Api
class StuffsController < ApiController
before_action :authenticate_user!
...
end
end
API Controller
class ApiController < ApplicationController
include DeviseTokenAuth::Concerns::SetUserByToken
end
User model
class User < ActiveRecord::Base
# Include default devise modules.
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
include DeviseTokenAuth::Concerns::User
end
Finally don't forget to configure the gem in the corresponding initializer.
这篇关于基于令牌的Rails JSON API认证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!