Warning, highly experimental I’ve recently been needing a lot of temporary tokens for various projects. These are small Sinatra app auth tokens, API auth tokens, and the like. They’re small, self-contained projects, and I don’t want the overhead of tracking and expiring tokens in a database or redis.

I began to wonder if there was a way to create “self-destructing” tokens which would automatically expire based upon nothing but their own value. No need to store them anywhere on a server. Give it to the client, get it back, and see if it still is (or ever was) valid. I couldn’t find anything like this, so I came up with MortalToken.

Example Sinatra app

require 'sinatra'
require 'mortal-token'

# Set your secret key. Keep it secret; keep it safe!
MortalToken.secret = 'asdf092$78roasdjfjfaklmsdadASDFopijf98%2ejA#Df@sdf'

post '/login' do
  if login_ok?
    # Create a new token, store the resulting hash and salt in the session
    token = MortalToken.new
    session[:token] = token.hash
    session[:salt] = token.salt

    redirect '/secret'
  end
end

get '/secret' do
  # Attempt to reconstitute the original token, using the salt
  token = MortalToken.new(session[:salt])

  # Test if the token still is (or ever was) valid
  if token == session[:token]
    'Welcome!'
  else
    'Go away!'
  end
end

It seems to work well. As long as the secret key is kept safe, I don’t see any holes (assuming everything is being transmitted securely). But I freely admit I’m no cryptographer or security export. Feedback is welcome.