Elm, Rails and session cookies

For my first experiments with Elm, I started to write a small app that fetched data from an existing Rails app which uses Cookie sessions for authentication.

I started down the path of looking for how Elm and more specifically the elm-http package handles cookies, and came across a package for Elm for managing cookies, which is unpublished as the authors’ conclusion was that cookies are rarely useful.

I could see the Rails session Set-Cookie header in the response with the information I needed, so I started to look at extracting that information and sending it as a Set-Cookie header on the request. However, the response headers I was seeing in Elm didn’t include it. This is because browser security blocks scripts making Http calls with XMLHttpRequest from accessing cookies – a good thing.

Instead of direct access to cookie data, the handling of cookies is left to the browser. By setting withCredentials to true on the XMLHttpRequest, the browser will send the session cookie sent by Rails app back on future requests. This is especially important for cross-site requests for example when you are developing locally but making API requests from a remote server.

The elm-http package supports setting withCredentials in the settings passed to Http.send.

defaults =
Http.defaultSettings

withCredentials =
{ defaults | withCredentials = True }

task =
Http.send
withCredentials
(corsGet url)

(apologies, the code formatter has lost some of the white spacing)

The final trick is to make sure you set withCredentials to be True on all calls, in particular the call where you authenticate to the server and get the session cookie back for the first time.

Finally, it would seem that this isn’t the best way for Javascript based API calls to authenticate, and JSON Web Tokens (JWT) seem to be a much better approach.

Leave a Reply

Your email address will not be published. Required fields are marked *