simple_authentication_tokenの使い方

トークンを簡単に発行してくれるsimple_authentication_tokenの使い方です。

github.com

deviseから削除されたtoken発行機能

deviseからtoken発行機能が削除されました。そのためtokenを発行したい場合は、このgemを使うと簡単にできます。

gem install

gem 'simple_token__authentication'
$ bundle install

authentication_tokenカラムの追加

該当するテーブルにauthentication_tokenカラムを追加しましょう。

rails g migration add_authentication_token_to_users "authentication_token:string{30}:uniq"
rake db:migrate

該当するmodelにgemを適用する

今回はユーザーモデルに適応してみたいと思います。

models/user.rb

class User < ActiveRecord::Base
acts_as_token_authenticatable

これだけです!

該当するコントローラーにgemを適用する

class ApplicationController < ActionController::Base # or ActionController::API
# or ActionController::Metal
# ...
acts_as_token_authentication_handler_for User

APIを作っているときはCSRFをoffにしましょう。

class ApplicationController < ActionController::Base # or ActionController::API
# or ActionController::Metal
# ...
# Security note: controllers with no-CSRF protection must disable the Devise fallback,
# see #49 for details.
acts_as_token_authentication_handler_for User, fallback: :none

やってくれること

authentication_tokenカラムがnilのときに、tokenを発行してくれます!それはbefore_saveでauthentication_tokenカラムがblank?のときに、新しいgemを発行してくれるメソッドがあるからです。
しかも、tokenを生成したときに他のユーザーとかぶっていないかチェックして、仮にかぶってしまった場合はtokenを生成しなおすようになっています!

simple_token_authentication/acts_as_token_authenticatable.rb at master · gonzalo-bulnes/simple_token_authentication · GitHub

sign inの度にtokenを書き換えたい場合は?

このやり方もissuesに書いてました。

userモデルにauthentication_tokenカラムをnilにするメソッドを作成します。

class User < ActiveModel
acts_as_token_authenticatable
# Invalidate the user's authentication token and set a new one
#
# user - a token authenticatable User
#
# Returns the user's new authentication token
def reset_authentication_token!
self.authentication_token = nil
self.save # automatically generates a new authentication token 
end

該当するcontrollerのアクションで、このメソッドを呼ぶだけです!

class SubscriptionsController < ActionController
# the first time users' credential are present and correct they will get signed in
acts_as_token_authentication_handler_for User
def renew
# do whatever you need to renew the user's subscrption
current_user.reset_authentication_token!
# then build the response as usual
# ...
end
# ...
end

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です