Programming Journal

学習したことの整理用です。

【Rails】【API】雑多なメモ

response.headers

HTTPheaderAccessTokenにtokenをセットしたいとき

Provides access to the request's HTTP headers, for example:

response.headers['AccessToken'] = token

Action Controller の概要 - Railsガイド

ActionDispatch::Request

class Net::HTTPResponse (Ruby 2.7.0 リファレンスマニュアル)

POSTMANで確認すると、ちゃんとheadersにtokenが格納されています。

f:id:Study-Diary:20201125152215p:plain
header

HTTPのトークン認証

authenticate_or_request_with_http_tokenを使う
include ActionController::HttpAuthentication::Token::ControllerMethodsモジュールをincludeするのを忘れないこと。

module Api
  module V1
    class BaseController < ApplicationController
      include ActionController::HttpAuthentication::Token::ControllerMethods

      before_action :authenticate

      # サブクラスで使うのでprotected
      protected

      # ApiKey.activeで有効期限内に限定している(activeというスコープを別で定義している)
      # &.userで、レシーバがnilではない場合にApikeyの情報から関連するuserを特定して返す。
      def authenticate
        authenticate_or_request_with_http_token do |token, _options|
          @_current_user ||= ApiKey.active.find_by(access_token: token)&.user
        end
      end

      # @_というのは、インスタンス変数を、ローカルキャッシュとして扱う場合、_をプレフィックスとして付ける慣習がある
      # current_userメソッドを使ってほしいので、直接@current_userを使わないように明示している。
      def current_user
        @_current_user
      end

      private

      def form_authenticity_token; end
    end
  end
end

Rails による API 専用アプリケーション - Railsガイド

ActionController::HttpAuthentication::Token

Rubyの@_って何?? - Qiita

Rails-APIでsorceryを使ったらundefined local variable or method `form_authenticity_token'と怒られた - Qiita