I have a simple web app built using Sinatra, with sessions enabled.
If I am understanding correctly, the session data is stored in an encoded cookie. As the session data changes, the value of the cookie will change also.
I need a unique session identifier that remains constant through the entire session. Is there such an identifier. Or must I create my own unique value and store it in the session myself?
Thanks!
EDIT: In a comment below I thought of a useful comparison. If I had a Java servlet, I would use the JSESSIONID as a unique identifier. I need a Sinatra equivalent to the JSESSIONID.
A session ID is a unique number that a Web site's server assigns a specific user for the duration of that user's visit (session). The session ID can be stored as a cookie, form field, or URL (Uniform Resource Locator). Some Web servers generate session IDs by simply incrementing static numbers.
Because this is one of the first Google results for the subject and it contains no actual examples, here is a simple way to create your own SESSION_ID. We're relying on probability and cryptographically secure randomness to keep our IDs unique.
This is the only thing I put in my cookies. I keep all the other data on the back end to prevent anyone from tampering with it.
require 'sinatra'
require 'securerandom'
# The configuration here is just an example. Use your own secret, etc.
use Rack::Session::Cookie, :key => 'SESSION_ID',
:expire_after => 60*60*24, # == one day
:secret => 'This one time, at band camp...'
before do # Before every request, make sure they get assigned an ID.
session[:id] ||= SecureRandom.uuid
end
get '/' do # Show off your new ID.
"Your ID is #{session[:id]}"
end
In a sinatra app if you print out session.keys, you'll see there is a "session_id" that contains the unique id for the current session. You can access this 64 byte string as session["session_id"].
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With