Pregunta

I am using a token based authentication for a rails json api. I have rewritten methods in the devise sessions and registrations controller since devise deprecated the token_authenticable module. Is devise in this state unnecessary for an api? Is devise still more secure for a purpose like this in which I'm writing the token authentication myself?

For example, according to a devise gist, I should use the following code to authenticate a user from a token:

  def authenticate_user_from_token!
    email = params[:user_email].presence
    user  = email && User.find_by_email(email)
    if user && Devise.secure_compare(user.authentication_token, params[:auth_token])
      sign_in user, store: false
    end
  end

I believe params[:auth_token] would not work for an api that send the token in the header. I'm also not sure what purpose sign_in user would serve in a json api. I can either keep devise and continue to modify it for tokens or follow e.g. https://github.com/danahartweg/authenticatable_rest_api/ for a custom solution.

¿Fue útil?

Solución

The answer to your question depends on how much security you want. Using a auth token stored in the user table is a somewhat low level of security, like username/password. Over an https connection, it's fairly difficult for a casual attacker to get what they need, but if they do, it's vulnerable to replay attacks. Even if you implement a rolling key (change it often), there must be some way to communicate the new key to the client, which that same attacker could intercept. That said, if you want to pass the auth_token in the header, you can retrieve it in your controller using something like this: request.headers[:auth_token].

HMAC is a considerably more secure method that prevents replay attacks by incorporating a shared secret between the client and server and a timeout for the signed request. See my answer to this question for more about HMAC and a Rails server with an iPhone client.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top