Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting unique session ID in Sinatra

Tags:

ruby

sinatra

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.

like image 290
Dave Isaacs Avatar asked Apr 11 '11 15:04

Dave Isaacs


People also ask

Is session ID unique?

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.


2 Answers

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
like image 155
Qsario Avatar answered Oct 21 '22 04:10

Qsario


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"].

like image 25
Don Park Avatar answered Oct 21 '22 06:10

Don Park