triauth for Sinatra
A complete sign-in flow for a Sinatra app in about 50 lines, with Sinatra's cookie session holding the challenge.
- Library
- triauth-ruby
- Requires
- Ruby 3.2 or newer
- Install
gem install --pre triauth
Intro
The official triauth-ruby open-source library can be used with Sinatra based web applications.
Sign-in is two simple calls to the library, with no passwords to store, protect, or reset.
Integrate triauth with your application in an afternoon and boost your metrics by offering a simple, effortless way for users to sign in and try it. Once you do, make sure to let us know - we love featuring integrations on the triauth project's website.
Get started
This guide shows you how to add "Sign in with triauth" to a Sinatra app with triauth-ruby. At the end you have an app with a sign-in form that sends the user to their authenticator and signs them in when they approve. It takes about fifteen minutes.
How sign-in works
A sign-in has three stages, and your app calls Triauth.authenticate twice:
# 1. request: start a sign-in for the identifier the user typed
result = Triauth.authenticate({ identifier: identifier, callbackUrl: callback_url })
# 2. redirect: keep the challenge on the server, send the user to their authenticator
session[:challenge] = result[:challenge]
redirect result[:redirectUrl]
# 3. verify: the browser comes back to callbackUrl with a response
result = Triauth.authenticate({ challenge: session[:challenge], response: response })
session.delete(:challenge) # a challenge is good for one attempt only
session[:identifier] = result[:identifier] if result[:authenticated]We will follow these stages in this tutorial, and start by building a sign-in page, then follow the request through the authenticator, and finally verify the received response. See the sign-in flow guide for more details.
Before you start
- Ruby 3.2 or newer. Check with
ruby --version. - A triauth identity of your own, set up in the browser you test with. See Set up your identity.
- An empty folder, or an existing Sinatra project.
1. Install the gems
Install triauth-ruby, then Sinatra and the two gems Sinatra serves the app with, Puma and rackup. While triauth-ruby is in beta, --pre picks its prerelease. It stays on its own line, so that it does not pull prereleases of the other gems.
gem install --pre triauth
gem install sinatra puma rackup2. Create the sign-in page
Create app.rb. It serves a sign-in form at /, and the form posts the identifier to /login, where stages 1 and 2 run.
require 'triauth'
require 'sinatra'
# the address the authenticator sends the browser back to, never built from request headers
CALLBACK_URL = 'http://localhost:3000/callback' # your public address in production
set :port, 3000
# sessions in an encrypted cookie, with a new secret on every start, so a restart signs everyone out
enable :sessions
# the home page: the identifier when signed in, the sign-in form otherwise
get '/' do
return "Signed in as #{session[:identifier]}" if session[:identifier]
error = session[:error] ? session[:error][:message] : ''
session.delete(:error)
<<~HTML
<form action="/login" method="post">
<input name="identifier" placeholder="you@example.com">
<button>Sign in with triauth</button>
<p style="color: red">#{error}</p>
</form>
HTML
end
# the sign-in form posts here
post '/login' do
# make sure the sign-in is from this site's own pages
site = request.env['HTTP_SEC_FETCH_SITE']
halt 403 if site && site != 'same-origin'
identifier = params[:identifier].to_s
# 1. request
result = Triauth.authenticate({ identifier: identifier, callbackUrl: CALLBACK_URL })
# 2. redirect, when the result holds a challenge
if result[:challenge]
session[:challenge] = result[:challenge] # kept on the server, where the user cannot change it
redirect result[:redirectUrl]
end
session[:error] = result[:error] # an invalid identifier, or a domain that is not set up for triauth
redirect '/'
endThe /login route runs stages 1 and 2. Triauth.authenticate reads the DNS records of the identifier's domain, finds the user's authentication endpoint there, and returns a challenge and a redirectUrl. If the identifier is malformed, or its domain is not set up for triauth, it returns an error instead, and the form shows its message. The challenge goes into the session, and the browser is redirected to the authenticator. The result is a Hash with Symbol keys, named as in triauth-js, so the address to redirect to is result[:redirectUrl].
A few parts of this file matter for your own app too.
The session keeps the challenge between the two calls, where the user cannot change it. Sinatra keeps the session in an encrypted cookie, with a new secret on every start, which is enough for a tutorial. In your app, set session_secret from your configuration, so that sessions survive a restart. Sinatra sets no SameSite attribute on the cookie, and the browser sends it when the authenticator brings the user back to your site.
The sec-fetch-site check refuses a sign-in form that another website posted. Without it, another website could post an attacker's identifier to /login from the user's browser, and your app would sign the user in to the attacker's account. Browsers set this header to same-origin for a form from your own pages. A CSRF token does the same job. Sinatra's own protection middleware does not stop such a request: by default it clears the session and lets the request through. See Stage 1 of the sign-in flow.
CALLBACK_URL is fixed configuration. Do not build it from the Host header of the request, which the client controls.
The redirect to the authenticator must keep the Referer header, which the authenticator compares with your callback URL. The browser's default policy sends your origin, so this works unless your app sets a no-referrer policy.
Start the app:
ruby app.rbOpen http://localhost:3000 in the browser where your identity is set up, and enter your identifier.
Checkpoint
You should see the form, then your authenticator asking you to approve a sign-in to http://localhost:3000/.
3. Approve the request
The browser is now at the user's authenticator, with the challenge in the URL. The authenticator shows the address of your website and the identifier, and asks the user to approve or deny.
Click Approve.
Checkpoint
The browser lands on http://localhost:3000/callback?response= followed by the encrypted response, and the page says "Sinatra doesn’t know this ditty." The app has no route for /callback yet. The next step adds it.
4. Receive the response and sign the user in
In app.rb, add the callback route after the /login route.
# the sign-in form posts here
post '/login' do
# ...
end
# 3. verify: the authenticator sends the browser back here, with the response in the query string #
get '/callback' do
result = Triauth.authenticate({ challenge: session[:challenge].to_s, response: params[:response].to_s })
session.delete(:challenge) # a challenge is good for one attempt only #
if result[:authenticated]
session[:identifier] = result[:identifier]
else
session[:error] = result[:error] # denied, expired, or not verified #
end
redirect '/' # always redirect, so that the response does not stay in the address bar #
endThis route runs the response verification stage. It reads response from the query string and passes it to Triauth.authenticate together with the challenge from the session. The library decrypts the response with the key in the challenge, reads the identity records again, and checks the signature against the public keys published there. On success, result[:authenticated] is true and result[:identifier] is the verified identifier, which the route stores in the session. On failure, result[:error] says why, with a code such as request_denied or request_expired.
The challenge is deleted from the session before the result is read, so that one challenge serves one attempt. The two to_s calls pass a missing challenge or response as an empty string, which the library reports as "Invalid challenge", for example after a lost session or the Back button. The route always ends with a redirect to /, where the home page shows the signed-in state, and the response does not stay in the address bar. Receiving the response explains how the response reaches /callback and what it leaves in your logs.
The result has more fields than the identifier, such as the name of the device that signed and a session key for the requests that follow. Read Stage 3 of the sign-in flow for the full list and what to store.
Stop the app with Ctrl+C, start it again, and sign in once more:
ruby app.rbCheckpoint
After you approve, you should see the page "Signed in as" followed by your identifier. If you deny the request, the form comes back with "Request has been denied" in red.
5. Celebrate 🎉
You now have a fully functional "Sign in with triauth" flow. But don't stop yet - there is so much more you can do with triauth! You can periodically validate sessions with Triauth.check and Triauth.ping, ask for terms acceptance with Triauth.sign, and verify that the user is not a robot with Triauth.attest. See the triauth-ruby README to learn more, or visit the triauth playground.
The complete app.rb
require 'triauth'
require 'sinatra'
# the address the authenticator sends the browser back to, never built from request headers
CALLBACK_URL = 'http://localhost:3000/callback' # your public address in production
set :port, 3000
# sessions in an encrypted cookie, with a new secret on every start, so a restart signs everyone out
enable :sessions
# the home page: the identifier when signed in, the sign-in form otherwise
get '/' do
return "Signed in as #{session[:identifier]}" if session[:identifier]
error = session[:error] ? session[:error][:message] : ''
session.delete(:error)
<<~HTML
<form action="/login" method="post">
<input name="identifier" placeholder="you@example.com">
<button>Sign in with triauth</button>
<p style="color: red">#{error}</p>
</form>
HTML
end
# the sign-in form posts here
post '/login' do
# make sure the sign-in is from this site's own pages
site = request.env['HTTP_SEC_FETCH_SITE']
halt 403 if site && site != 'same-origin'
identifier = params[:identifier].to_s
# 1. request
result = Triauth.authenticate({ identifier: identifier, callbackUrl: CALLBACK_URL })
# 2. redirect, when the result holds a challenge
if result[:challenge]
session[:challenge] = result[:challenge] # kept on the server, where the user cannot change it
redirect result[:redirectUrl]
end
session[:error] = result[:error] # an invalid identifier, or a domain that is not set up for triauth
redirect '/'
end
# 3. verify: the authenticator sends the browser back here, with the response in the query string
get '/callback' do
result = Triauth.authenticate({ challenge: session[:challenge].to_s, response: params[:response].to_s })
session.delete(:challenge) # a challenge is good for one attempt only
if result[:authenticated]
session[:identifier] = result[:identifier]
else
session[:error] = result[:error] # denied, expired, or not verified
end
redirect '/' # always redirect, so that the response does not stay in the address bar
endWith Bundler
If your project has a Gemfile, add the four gems there instead of installing them by hand:
source "https://rubygems.org"
gem "triauth", ">= 1.0.0.beta"
gem "sinatra"
gem "puma"
gem "rackup"Then install them and start the app through Bundler:
bundle install
bundle exec ruby app.rbNext steps
- Read The sign-in flow for what the result contains and what to store from it.
- Read Sessions and sign-out to confirm during the session that the device is still trusted, with
Triauth.checkandTriauth.ping. - Read Configuration for the DNS resolvers, the DNSSEC flag, and caching on a busy server.
- See triauth for Ruby on Rails for the same sign-in in a Rails app, and triauth for Rack for a plain Rack application with no framework.
- The triauth-ruby README has the full API, including
Triauth.whoisto look up an identity, signatures, stamps, and attestations. - The Playground lets you try the protocol in your browser before you write code.
All logos and trademarks belong to their respective owners and do not imply affiliation or endorsement of the organization or product by triauth, nor vice versa. The content provided on this page may include information from third-party sources. We do not assume any responsibility for the completeness, correctness, or applicability of the information. You should independently verify any details before relying on them.