user3456978
user3456978

Reputation: 248

user_Id Session Secure ? Hartl

In Hartl's tutorial we set the session as a cookie stored as a hashed version of the user_id. We then compare the unhashed cookie to a user.id

https://www.railstutorial.org/book/log_in_log_out

def log_in(user)
    session[:user_id] = user.id
  end

Is this secure? Couldn't I session hash random user_id numbers to generate a cookie myself that I could then use to log in as another random user?

Upvotes: 1

Views: 167

Answers (2)

Frederick Cheung
Frederick Cheung

Reputation: 84132

Depending on the version of rails the data stored by the cookie store is either cryptographically signed (users can see all the data, but modifications are detected and rejected) or signed and encrypted (modifications are still rejected, but users can't what you're storing in the session). In both cases if you tamper with the session data you'll get an exception when rails tries to load the session.

You can use these protections for regular cookies to, by using cookies.signed or cookies.encrypted in your controller.

The key used for the encryption/signing is derived from the secret_key_base setting (in recent versions of rails, this is in config/secrets.yml). If an attacker were have access to this setting then they could forge cookie store session data.

Upvotes: 2

Joe Marion
Joe Marion

Reputation: 406

Normally you wouldn't want to expose user.id. The way that sessions work is that session[:user_id] will create a temporary cookie and will automatically encrypt the user.id. It's one of the differences between session[:user_id] vs cookie[:user_id]. It will then decrypt automatically on the next page. So technically it is still considered secure.

Upvotes: 0

Related Questions