Search code examples
ruby-on-railsapi-key

Submit API key in form?


I have a json API for some resources owned by users. I have protected API access using an API access key as described in this railscast: http://railscasts.com/episodes/352-securing-an-api

This works fine, I have a unique key for each user that they have to submit when they want to add/update/delete a resource. The problem I'm having is, aside from the API, users should be able to edit the resources from a Web form. This does not work though, since the form does not submit the API key in the header and so access is denied.

Is there a way to get the form to send the access key for the user since they are logged in already? Or perhaps I am going about it wrong? Perhaps I should check if there is a active session and in that case use that as authentication instead of the API Key?


Solution

  • Is there a way to get the form to send the access key for the user since they are logged in already?

    The API access key can be sent for the user by including it as a hidden field in the form. Once you receive it, you can compare it with the assigned access key for the logged-in user.

    But think about your customers and your business. Including the API key in a clear-text within the form is like giving the hackers, literally, access to alter anything they want, especially if HTTPS is not configured.

    Perhaps I should check if there is a active session and in that case use that as authentication instead of the API Key?

    Yes, this is one of the secure methods to do it. The first method you mentioned is not secure at all. Don't put any thing related to authenticating in a place where it can be easily altered (form, cookie).

    If you wish, you can use both session-based authentication with API access Key. How? Lets say you generate an API access key with expiry date for each modification request. Each modification is required to be submitted within x minutes after it is triggered. Once submitted, you authenticate the user against session and the modification against API. This is just an example.