LoginSignup
1
2

More than 5 years have passed since last update.

Rails5, devise_token_auth/deviseで暗号化方式を変更する

Posted at

背景

devise_token_authを使って認証のあるアプリのAPIを開発している。色々あって、既存を活用しなくてはいけないのだが、その暗号化方式がデバイスで使われているものとは異なっていて、デバイス暗号化方式を変更する必要が出てきた。

使ったgemはdevise-encryptableなのですが、このREADMEが古すぎてこの通りでは動かなかったのでメモ。

ちなみにdevise_token_authでも認証周りは基本的にdeviseに依存しているので、以降deviseのみについて言及する。devise_token_authについても同様に動くことは確認済みなので安心してほしい。

deviseのgithubのwikiに導入方法が書いてあるのだが、この通りにやってもちゃんと動かないので注意が必要。

環境

MaxOSX: 10.12.3
Rails 5.0.1 (API mode)
devise_token_auth (0.1.40)
devise (4.2.0)
devise-encryptable (0.2.0)

手順

インストール

Gemfile.
gem "devise-encryptable"

そしてbundle install

カラムを用意してあげる

ターミナルにて以下を実行

rails g migration add_column_to_users
/db/migrate/2017XXXXX_add_column_to_users.rb
class AddColumnToUser < ActiveRecord::Migration[5.0]
  def change
    add_column :users, :password_salt, :string
  end
end

ターミナルにて

rails db:migrate

railsプロジェクトに必要事項の追加

以下のそれぞれのファイルに追加する。

config/initializers/md5.rb
# 勝手に作られないので自分で作ること

require 'digest/md5'

module Devise
  module Encryptable
    module Encryptors
      class Md5 < Base
        def self.digest(password, stretches, salt, pepper)
          str = [password, salt].flatten.compact.join
          Digest::MD5.hexdigest(str)
        end
      end
    end
  end
end
app/models/user.rb
class User < ActiveRecord::Base
  # 追加
  devise :encryptable
end

以上でdeviseの使う暗号化方式をmd5に上書きすることができる。登録処理、ログイン処理までは試しているからおそらく問題ない。password_saltカラムが必要な理由としてはこれを参照するといいだろう。

参考

devise/wiki
github/devise_encryptable

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2