LoginSignup
12
13

More than 5 years have passed since last update.

deviseで認証しているRailsアプリケーションにcurlする

Posted at

やりたいこと

ローカルで開発中のRailsアプリケーションに対してcurlでユーザ認証して、ログインが必要なエンドポイントのAPIを叩きたい。

以下の条件のアプリケーションを前提にしています。

  • 認証にdeviceを使っている
  • session管理をcookie(Railsデフォルト)で行っている
  • csrfトークンは考慮していないので、:point_down: のようにチェックを一時的にスキップさせた
app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  skip_before_action :verify_authenticity_token, if: -> {request.format.json?}
end

方法

ログイン

ログインが成功し、cookieにログイン情報が格納される

curl -H 'Content-Type: application/json' \
  -X POST http://localhost:3000/users/sign_in \
  -d '{"user":{"email":"your_email_address@example.com","password":"your_password"}}' \
  -c cookie

:point_down: なレスポンスが返る

<html><body>You are being <a href="http://localhost:3000/">redirected</a>.</body></html>

ログインが必要なAPIにアクセス

-b cookie でcookieをつけてリクエストする、成功するはず:thumbsup:

curl -H 'Content-Type: application/json' \
  -X GET 'http://localhost:3000/api/items' \
  -b cookie
12
13
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
12
13