Rails API With Authentication Simple Tutorial

Installation

Add the following to your Gemfile:

gem 'devise_token_auth'
gem 'devise', '~> 4.0.0.rc1'

Then install the gem using bundle:

bundle install

Creating User Model and Migration

Next, let's create a model for authentication.

rails g devise_token_auth:install User auth

It will return such things at console:

Running via Spring preloader in process 78994
      create  config/initializers/devise_token_auth.rb
      create  db/migrate/20160328130022_devise_token_auth_create_users.rb
      create  app/models/user.rb
      insert  app/controllers/application_controller.rb
        gsub  config/routes.rb

Since we don't need omniauth at the moment, we should remove the configure(:omniauthable) in model:

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

Migration comes next!

rake db:migrate

We may get an error while using devise that version is lower that 4.0.0:

DEPRECATION WARNING: alias_method_chain is deprecated. Please, use Module#prepend instead.....
NameError: uninitialized constant ActionController::RackDelegation...

Routes

Run this command to show all routes:

rake routes

The result is:

Prefix Verb URI Pattern Controller#Action
new_user_session GET /auth/sign_in(.:format) devise_token_auth/sessions#new
user_session POST /auth/sign_in(.:format) devise_token_auth/sessions#create
destroy_user_session DELETE /auth/sign_out(.:format) devise_token_auth/sessions#destroy
user_password POST /auth/password(.:format) devise_token_auth/passwords#create
new_user_password GET /auth/password/new(.:format) devise_token_auth/passwords#new
edit_user_password GET /auth/password/edit(.:format) devise_token_auth/passwords#edit
PATCH /auth/password(.:format) devise_token_auth/passwords#update
PUT /auth/password(.:format) devise_token_auth/passwords#update
cancel_user_registration GET /auth/cancel(.:format) devise_token_auth/registrations#cancel
user_registration POST /auth(.:format) devise_token_auth/registrations#create
new_user_registration GET /auth/sign_up(.:format) devise_token_auth/registrations#new
edit_user_registration GET /auth/edit(.:format) devise_token_auth/registrations#edit
PATCH /auth(.:format) devise_token_auth/registrations#update
PUT /auth(.:format) devise_token_auth/registrations#update
DELETE /auth(.:format) devise_token_auth/registrations#destroy
user_confirmation POST /auth/confirmation(.:format) devise_token_auth/confirmations#create
new_user_confirmation GET /auth/confirmation/new(.:format) devise_token_auth/confirmations#new
GET /auth/confirmation(.:format) devise_token_auth/confirmations#show
auth_validate_token GET /auth/validate_token(.:format) devise_token_auth/token_validations#validate_token

As shown above, /auth includes all the action related to authentication.

Authenticate

Let's create a Listing model to show how it works.

rails g scaffold listing content:text title:string

After migration, add one line code to application_controller.rb

#application_controller.rb
class ListingsController < ApplicationController
  before_action :authenticate_user!
  ...
end

All right, you should get 401 while visit http://localhost:3000/listings/1.

Sign up

Firstly, wo don't need users confirm their registration with their own email, so we remove :confirmable in models/user.rb.

Sending a post requset to http://localhost:3000/auth with the parameters(email, password, password_confirmation) would create a user.

curl -X POST -H "Cache-Control: no-cache" -H "Postman-Token: 3a9aa5e9-2ba7-7de3-66b4-ec3a85f6ddd0" "http://localhost:3000/auth?email=zhen6939@163.com&password=51190109&password_confirmation=51190109"

Sign in

According to the routes sheet, implement 'sign in' needs a post request to */auth/sign_in *:

curl -X POST -H "Cache-Control: no-cache" -H "Postman-Token: 2c7e777b-031d-c958-79e7-04ef75fe9bd5" "http://localhost:3000//auth/sign_in?email=zhen6939@163.com&password=51190109"

It returns access-token, client, expiry, token-type, uid.

param description
access-token This serves as the user's password for each request. A hashed version of this value is stored in the database for later comparison. This value should be changed on each request.
client This enables the use of multiple simultaneous sessions on different clients. (For example, a user may want to be authenticated on both their phone and their laptop at the same time.)
expiry The date at which the current session will expire. This can be used by clients to invalidate expired tokens without the need for an API request.
uid A unique value that is used to identify the user. This is necessary because searching the DB for users by their access token will make the API susceptible to timing attacks.

Using those params properly, we can kindly keep user login at different devices.

How the authentication works

As shown above, access-token is used as 'password' for each request. By default, It should be changed after every request to server. At other words, every response of request to server will return different access-token. It means that every request you sent should include access-token which you got at previous request.

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末权谁,一起剝皮案震驚了整個(gè)濱河市剩檀,隨后出現(xiàn)的幾起案子憋沿,更是在濱河造成了極大的恐慌,老刑警劉巖沪猴,帶你破解...
    沈念sama閱讀 211,123評(píng)論 6 490
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件辐啄,死亡現(xiàn)場離奇詭異,居然都是意外死亡运嗜,警方通過查閱死者的電腦和手機(jī)壶辜,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,031評(píng)論 2 384
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來担租,“玉大人砸民,你說我怎么就攤上這事岭参。” “怎么了?”我有些...
    開封第一講書人閱讀 156,723評(píng)論 0 345
  • 文/不壞的土叔 我叫張陵,是天一觀的道長嵌莉。 經(jīng)常有香客問我沿癞,道長椎扬,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 56,357評(píng)論 1 283
  • 正文 為了忘掉前任天吓,我火速辦了婚禮汰规,結(jié)果婚禮上色解,老公的妹妹穿的比我還像新娘在抛。我一直安慰自己票唆,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,412評(píng)論 5 384
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般瞒渠。 火紅的嫁衣襯著肌膚如雪嫩痰。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,760評(píng)論 1 289
  • 那天晰搀,我揣著相機(jī)與錄音乡翅,去河邊找鬼。 笑死腺毫,一個(gè)胖子當(dāng)著我的面吹牛急黎,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 38,904評(píng)論 3 405
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢(mèng)啊……” “哼!你這毒婦竟也來了猎唁?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 37,672評(píng)論 0 266
  • 序言:老撾萬榮一對(duì)情侶失蹤兔毒,失蹤者是張志新(化名)和其女友劉穎豪嗽,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 44,118評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡樱溉,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,456評(píng)論 2 325
  • 正文 我和宋清朗相戀三年逻族,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片枪芒。...
    茶點(diǎn)故事閱讀 38,599評(píng)論 1 340
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡货徙,死狀恐怖蠢棱,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情猾担,我是刑警寧澤圾叼,帶...
    沈念sama閱讀 34,264評(píng)論 4 328
  • 正文 年R本政府宣布,位于F島的核電站唐础,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏呀邢。R本人自食惡果不足惜蝉衣,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,857評(píng)論 3 312
  • 文/蒙蒙 一啦膜、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸脸候。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,731評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽运沦。三九已至,卻和暖如春配深,著一層夾襖步出監(jiān)牢的瞬間携添,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 31,956評(píng)論 1 264
  • 我被黑心中介騙來泰國打工凉馆, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留薪寓,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 46,286評(píng)論 2 360
  • 正文 我出身青樓澜共,卻偏偏與公主長得像,于是被迫代替她去往敵國和親锥腻。 傳聞我的和親對(duì)象是個(gè)殘疾皇子嗦董,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,465評(píng)論 2 348

推薦閱讀更多精彩內(nèi)容