LoginSignup
8
4

More than 3 years have passed since last update.

devise-token-authでaccess-tokenをresponseで取得できない

Last updated at Posted at 2020-05-11

今回発生した問題

ページ内でrequest.headersにアクセスしても認証に必要なaccess-tokenclientが見当たらない。(apiをpostmanで叩いたら見れるのに...)

以下はpostmanに表示されたレスポンスヘッダ
スクリーンショット 2020-05-11 21.42.42.png

原因

APIとクライアントが異なるドメイン上にある場合に、RailsAPIにcross origin requestを許可する必要があり、exposeに関する記述が抜けていた。

参考にしたサイト

devise-token-authの公式ドキュメント(英語)
内容は同じですが、これを翻訳してくれているサイト
devise-token-authの公式ドキュメント(和訳)

修正したところ

ファイルの場所はプロジェクトによるが、CORSについて書かれているconfigファイルを書き換えた。今回は以下のファイルを修正する。

/back/config/initializers/cors.rb
Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins 'localhost:8080'

    resource '*',
      headers: :any,
      expose: ['access-token', 'uid', 'client'], #この行を新たに追加
      methods: [:get, :post, :put, :patch, :delete, :options, :head]
  end
end

最後に

この問題を解決するに当たり、様々な記事を行き来したが、最終的には公式ドキュメントであっさり解決してしまった。

8
4
1

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
8
4