Search code examples
ruby-on-railsrails-apihttponlycookie-httponly

Sending HTTPOnly cookie in response using Rails API application


Correct me if I'm wrong but cookies are just special Set-Cookie: headers, right? Maybe I'm missing something but that always seemed like the case to me. If I set up a Rails API application and want to support sending HTTPOnly cookies (e.g. headers also assume I've got CORS and everything on the client setup etc) I should be able to do this correct?

Basically, my questions are these:

  1. Does bringing back ActionDispatch::Cookies into my middleware and adding include ::ActionController::Cookies in my application controller totally defeat the purpose of an API application?
  2. If it does, can I just send an HTTPOnly cookie through the headers manually?
  3. And if that is so, is it a much bigger hassle to manage cookie headers manually? Is what I'm gaining from leaving the cookie middleware out out weigh handling them manually, if all I really need to do is send one HTTPOnly refresh token?

Solution

  • So I don't need to add back any middleware or include any classes for cookies. I can use reponse.set_header to send a cookie. However, this only lets you send one Set-Cookie header because it will overwrite the last header you set with Set-Cookie as the key. Instead you have access to response.set_cookie which will let you set multiple cookies with each set_cookie call. It also comes with some options that you can set that you would have to add to the value of the header you were sending manually with set_header.

    Here's an example I used that allowed me to send a cookie:

    response.set_cookie(
      :jwt,
      {
        value: 'this could be a token or whatever cookie value you wanted.',
        expires: 7.days.from_now,
        path: '/api/v1/auth',
        httponly: true
      }
    )
    

    Check the documentation for this method for other options because there are others.

    EDIT: I was having an issue where the cookie was getting sent in the response but not saved (still). It wasn't showing up in the cookie storage so I changed the path of the cookie getting sent to / and then it showed up. I deleted it and then changed the cookie's path to /my/real/path and it worked and was stored in cookie storage. Go figure.