Marius Butuc
Marius Butuc

Reputation: 18280

How do you use cURL to authenticate on a Rails application that uses Devise?

I want to test my rails web service using cURL, yet so far I could only do it while deactivating before_filter :authenticate_user!. But I'd like to log in a priori and then create, destroy etc.

I saw that with cURL you can authenticate and save the session info in a cookie, that you use for your following requests, yet I couldn't make it work with Devise: in my scenario, the user logs in using an email/password combination, so I'm trying:

curl \
  -X POST \
  -d '[email protected]&password=password' \
  -c cookie \
  http://localhost:3000/users/sign_in > out

and I get: ActionController::InvalidAuthenticityToken in Devise/sessionsController#create

Could somebody give me an idea / an example?

Thanks!

Upvotes: 14

Views: 13349

Answers (4)

Marius Butuc
Marius Butuc

Reputation: 18280

This works:

Authenticate:

curl -H 'Content-Type: application/json' \
  -H 'Accept: application/json' \
  -X POST http://localhost:3000/users/sign_in \
  -d "{'user' : { 'email' : '[email protected]', 'password' : 'password'}}" \
  -c cookie

Show:

curl -H 'Content-Type: application/json' \
  -H 'Accept: application/json' \
  -X GET http://localhost:3000/pages/1.xml \
  -b cookie

Upvotes: 23

Marius Butuc
Marius Butuc

Reputation: 18280

Got the following answer from José Valim:

If you have an web service, sign in should be done using HTTP Auth. If not, your option is to disable authenticity token on the session form, although not recommended.

Upvotes: 1

needto
needto

Reputation: 51

This is because Rails by default adds an authenticity token to forms to protect from malicious forgery of submitted parameters. As you do not supply this token with your request, rails does not accept it. You can bypass this with

skip_before_filter :verify_authenticity_token

in your controller, where authorization takes place, better even to limit it to the authorization action with :only.

Upvotes: 4

polarblau
polarblau

Reputation: 17744

Have you tried something like this (not tested):

curl --user name:password http://www.domain.com
curl --user name:password -f 'key=value' http://www.domain.com

Upvotes: 1

Related Questions