Skip to content

triauth for Ruby on Rails

A complete sign-in flow for a Rails app in one controller, three routes, and one view, with the Rails session holding the challenge.

Requires
Ruby 3.2 or newer, Rails 8
Install
bundle add triauth --version ">= 1.0.0.beta"

Intro

The official triauth-ruby open-source library can be used with Ruby on Rails 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 Ruby on Rails 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:

ruby
# 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_to result[:redirectUrl], allow_other_host: true

# 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 and Rails 8. Check with ruby --version and rails --version.
  • A triauth identity of your own, set up in the browser you test with. See Set up your identity.
  • A Rails app, new or existing. A new one comes from rails new triauth_demo.

1. Install the library ​

In the app's directory, add triauth-ruby to the Gemfile and install it. While triauth-ruby is in beta, the requirement admits the prerelease, which Bundler skips otherwise.

shell
bundle add triauth --version ">= 1.0.0.beta"

2. Create the sign-in page ​

In config/routes.rb, add the root route for the sign-in form and the route the form posts to, where stages 1 and 2 run.

ruby
Rails.application.routes.draw do
  root "sessions#new"
  post "/login", to: "sessions#create"
end

Create app/controllers/sessions_controller.rb.

ruby
class SessionsController < ApplicationController
  # 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

  # the home page: the identifier when signed in, the sign-in form otherwise
  def new
    render plain: "Signed in as #{session[:identifier]}" if session[:identifier]
  end

  # the sign-in form posts here, after Rails has checked its authenticity token
  def create
    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
      return redirect_to result[:redirectUrl], allow_other_host: true # the authenticator is another host
    end
    flash[:alert] = result[:error][:message] # an invalid identifier, or a domain that is not set up for triauth
    redirect_to root_path
  end
end

Create app/views/sessions/new.html.erb with the sign-in form.

erb
<%# a full-page form submission, so that the browser follows the redirect to the authenticator %>
<%= form_with url: "/login", data: { turbo: false } do |form| %>
  <%= form.text_field :identifier, placeholder: "you@example.com" %>
  <%= form.submit "Sign in with triauth" %>
  <p style="color: red"><%= alert %></p>
<% end %>

The create action 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 from the flash. 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]. Rails refuses a redirect to another host unless the call says allow_other_host: true.

A few parts of these files matter for your own app too.

The session keeps the challenge between the two calls, where the user cannot change it. Rails keeps the session in an encrypted cookie by default, which is enough for a sign-in. The cookie is SameSite=Lax, so the browser sends it when the authenticator brings the user back to your site.

Rails checks the authenticity token of every form post, and form_with puts the token into the form. Without the check, 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. Keep the check on for this route. See Stage 1 of the sign-in flow.

The form sets data: { turbo: false }. Turbo Drive submits a form with fetch, which cannot follow the redirect to the authenticator's origin, so without it nothing happens when you submit the form, and the console shows "Failed to fetch".

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:

shell
bin/rails server

Open 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 "Routing Error" with "No route matches [GET] "/callback"". The app has no route for /callback yet. The next step adds it.

4. Receive the response and sign the user in ​

In config/routes.rb, add the callback route.

ruby
Rails.application.routes.draw do
  root "sessions#new"
  post "/login", to: "sessions#create"
  get "/callback", to: "sessions#callback"
end

In app/controllers/sessions_controller.rb, add the callback action after create.

ruby
  # the sign-in form posts here, after Rails has checked its authenticity token
  def create
    # ...
  end

  # 3. verify: the authenticator sends the browser back here, with the response in the query string #
  def callback
    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
      flash[:alert] = result[:error][:message] # denied, expired, or not verified #
    end
    redirect_to root_path # always redirect, so that the response does not stay in the address bar #
  end
end

This action 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 action 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 action always ends with a redirect to the root path, 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:

shell
bin/rails server

Checkpoint

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 sessions_controller.rb, routes.rb, and new.html.erb

app/controllers/sessions_controller.rb

ruby
class SessionsController < ApplicationController
  # 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

  # the home page: the identifier when signed in, the sign-in form otherwise
  def new
    render plain: "Signed in as #{session[:identifier]}" if session[:identifier]
  end

  # the sign-in form posts here, after Rails has checked its authenticity token
  def create
    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
      return redirect_to result[:redirectUrl], allow_other_host: true # the authenticator is another host
    end
    flash[:alert] = result[:error][:message] # an invalid identifier, or a domain that is not set up for triauth
    redirect_to root_path
  end

  # 3. verify: the authenticator sends the browser back here, with the response in the query string
  def callback
    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
      flash[:alert] = result[:error][:message] # denied, expired, or not verified
    end
    redirect_to root_path # always redirect, so that the response does not stay in the address bar
  end
end

config/routes.rb

ruby
Rails.application.routes.draw do
  root "sessions#new"
  post "/login", to: "sessions#create"
  get "/callback", to: "sessions#callback"
end

app/views/sessions/new.html.erb

erb
<%# a full-page form submission, so that the browser follows the redirect to the authenticator %>
<%= form_with url: "/login", data: { turbo: false } do |form| %>
  <%= form.text_field :identifier, placeholder: "you@example.com" %>
  <%= form.submit "Sign in with triauth" %>
  <p style="color: red"><%= alert %></p>
<% end %>

Troubleshooting

Nothing happens when you submit the form ​

The form is missing data: { turbo: false }. Turbo Drive submits it with fetch, which cannot follow the redirect to the authenticator's origin, and the browser console shows "Failed to fetch". Add the attribute to form_with, as in the view above.

Next 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.check and Triauth.ping.
  • Read Configuration for the DNS resolvers, the DNSSEC flag, and caching on a busy server.
  • See triauth for Sinatra for the same sign-in in a Sinatra app, and triauth for Rack for a plain Rack application with no framework.
  • The triauth-ruby README has the full API, including Triauth.whois to 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.