Ruby on RailsでAPIトークンを発行して認証を行うまでと、RSpecでのテストの実装のサンプルです。
🍮Railsプロジェクトの準備
# プロジェクトの作成 rails new auth_test --api -d postgresql
# scaffoldで新しいモデルを生成 bundleexec rails g scaffold Article title:string content:text bundleexec rake db:setup bundleexec rake db:migrate
|
😼コントローラ側の実装
app/controllers/application_controller.rbにtokenの認証を実装します。
classApplicationController< ActionController::API include ActionController::HttpAuthentication::Token::ControllerMethods
before_action:authenticate
protected
defauthenticate authenticate_or_request_with_http_tokendo|token, options| token == ENV['API_TOKEN'] end end end
|
🐝認証のテスト
HTTPのリクエストのヘッダにトークン情報を渡します。
# サーバ起動 API_TOKEN=HOGE rails s
# 認証成功時 curl -s -X GET -H'Authorization: Bearer HOGE' -H'Content-Type:application/json' http://0.0.0.0:3000/articles/1 | jq . { "id": 1, "title":"test-title", "content":"test-content", "created_at":"2017-07-09T08:44:55.054Z", "updated_at":"2017-07-09T08:44:55.054Z" }
# 認証失敗時 curl -X GET -H'Authorization: Bearer FUGA' -H'Content-Type:application/json' http://0.0.0.0:3000/articles/1 HTTP Token: Access denied.
|
🐯RSpec
認証をサポートするモジュールspec/support/authentication_helper.rbを作成。
moduleAuthenticationHelper defauthenticate @env||= {} @env['HTTP_AUTHORIZATION'] ="Bearer#{ENV['API_TOKEN']}" end end
|
spec/rails_helper.rbに以下を追加。
RSpec.configuredo|config| config.include AuthenticationHelper,type::request end
|
Request Specでは次のように記述します。
it'should not allow access'do authenticate GET'/articles/1', {}, @env end
|
🐹参考リンク
🖥 VULTRおすすめ
「VULTR」はVPSサーバのサービスです。日本にリージョンがあり、最安は512MBで2.5ドル/月($0.004/時間)で借りることができます。4GBメモリでも月20ドルです。 最近はVULTRのヘビーユーザーになので、「ここ」から会員登録してもらえるとサービス開発が捗ります!