Curl doesn't persist cookies by default.
The way to do it, is to store cookies in a cookie file, and later use it with every request.
See http://ask.metafilter.com/18923/How-do-you-handle-authentication-via-cookie-with-CURL
Question
I have an API an in the Base Controller, which all my api controllers extend from I have the following snippets of code:
def restrict_api_access
authenticate_or_request_with_http_token do |token, options|
@api_key = ApiKey.find_by(api_key: token)
cookies.signed.permanent[:writer_auth] = @api_key.api_key
end unless current_user
end
def current_user
api_key = ApiKey.find_by(api_key: cookies.signed[:writer_auth])
if api_key
@current_user ||= User.find_by(id: api_key.xaaron_users_id)
end
end
Pretty straight forward and basic, if I do:
curl http://site.local.com:4000/api/v1/users -H 'Authorization: Token "0169d577d2845f3ea5e0fbf8ca2f444c"'
I get a list of users back. Woot.
Now I am thinking, based on the logic I have above I should now have a cookie created for this user based on the api key and now I should be able to do:
curl http://site.local.com:4000/api/v1/users
This how ever is not the case, while the on the first round through the cookie was created, life is grand and current_user
exists with a user object, on the second round through with no api key - the cookie is nil and I am issued 401 unauthorized.
This should not be happening, the cookie should not be deleted. What am I doing wrong?
Solution
Curl doesn't persist cookies by default.
The way to do it, is to store cookies in a cookie file, and later use it with every request.
See http://ask.metafilter.com/18923/How-do-you-handle-authentication-via-cookie-with-CURL