type1fool

type1fool

Implementing WebAuthn via LiveView

I am implementing passwordless authentication in an application, communicating the WebAuthn API via LiveView JS hooks. Over the past few days I have cleared a few hurdles as I’ve learned about the API from webauthn.guide.

The JS hook is properly sending back the attestation and client data to the LiveView. I can decode the client data and compare the challenge and origin. I can also decode the CBOR attestation, but this is where I get stuck. It’s not clear what to do with attestation_a and attestation_b.

The WebAuthn guide shows authData, ftm, and attStmt keys once the CBOR is decoded. I looked into decoding on the client, but that seemed to be a bad idea. The docs for Wax and CBOR have been helpful up to this point, and I’ve even dug into source code a bit. However, I’m not sure if the CBOR is being decoded correctly or what I need to do next to get authData and other attestation data.

If you have suggestions or examples, I would appreciate it. :heart_decoration:

Decoded Attestation

attestation_a: %{0 => <<3, 0, 116, 4, 0, 100, _REDACTED_>>, <<1, 0, 102>> => 2}
attestation_b: <<0, 110, 8, 0, 101, 9, 0, 103, _REDACTED_, 18, 0, 104, 19, 0, 97, 20, 0,
  117, 21, 0, 116, 22, 0, 104, 23, 0, 68, ...>>

LiveView Credentials Event Handler

def handle_event(
      "credentials",
      %{"attestation" => attestation, "clientData" => client_data, "type" => _type},
      %{assigns: %{challenge: server_challenge}} = socket
    ) do
  %{"challenge" => client_challenge, "origin" => client_origin} =
    client_data
    |> List.to_string()
    |> Jason.decode!()
    |> Map.update!("challenge", &Base.decode64!(&1, padding: false))

  # TODO: DECODE ATTESTATION
  {:ok, attestation_a, attestation_b} =
    attestation
    |> Base.decode64!()
    |> CBOR.decode()

  IO.inspect(attestation_a, label: "attestation_a")
  IO.inspect(attestation_b, label: "attestation_b")

  with true <- client_challenge == server_challenge,
        true <- client_origin == LiveShowyWeb.Endpoint.url() do
    # TODO: STORE PUB KEY AFTER VALIDATION PASSES
    # TODO: REDIRECT TO REFERRER OR HOME AFTER STORING PUB KEY
    {:noreply, put_flash(socket, :info, "Registration was successful")}
  else
    _ ->
      {:noreply, put_flash(socket, :error, "Registration failed")}
  end
end

HandleWebAuthn Hook

const HandleWebAuthn = {
  mounted() {
    console.info(`HandleWebAuthn mounted`)

    if (navigator.credentials) {
      console.info(`WebAuthn is supported by this browser.`)
      this.pushEvent("webauthn-supported", true)

      window.addEventListener("phx:challenge", async (data) => {
        const { appName, challenge, user } = data.detail
        const publicKey = {
          challenge: Uint8Array.from(challenge, c => c.charCodeAt(0)),
          rp: {
            name: appName,
            id: document.location.host,
          },
          user: {
            id: Uint8Array.from(user.id, c => c.charCodeAt(0)),
            name: user.email,
            displayName: user.username
          },
          pubKeyCredParams: [{ alg: -7, type: "public-key" }],
          timeout: 60000,
          attestation: "none",
          authenticatorSelection: {
            authenticatorAttachment: "platform",
            userVerification: "discouraged",
          },
        }

        const { response, type } = await navigator.credentials.create({ publicKey })
        const { attestationObject, clientDataJSON } = response
        const clientData = Array.from(new Uint8Array(clientDataJSON))

        const attestation = Array.from(new Uint8Array(attestationObject))
          .map(String.fromCharCode).join("")

        this.pushEvent("credentials", {attestation: btoa(attestation), clientData, type})
      })

    } else {
      console.error(`WebAuthn is not supported by this browser.`)
      this.pushEvent("webauthn-supported", false)
    }
  }
}

Marked As Solved

type1fool

type1fool

Whoo!!! This was wild!

It crossed my mind that I could double encode and decode the bytes on the server, and voila! It works!

Now, the challenge bytes are decoded successfully and reliably on the client, and the returned bytes match on the server. :tada:

%Wax.Challenge{
  acceptable_authenticator_statuses: [:fido_certified, :fido_certified_l1,
   :fido_certified_l1plus, :fido_certified_l2, :fido_certified_l2plus,
   :fido_certified_l3, :fido_certified_l3plus],
  allow_credentials: [],
  android_key_allow_software_enforcement: false,
  attestation: "none",
  bytes: <<70, 86, 81, 62, 234, 109, 239, 140, 123, 63, 220, 144, 15, 203, 189,
    151, 171, 128, 90, 251, 43, 189, 215, 68, 56, 67, 91, 233, 174, 85, 230,
    235>>,
  issued_at: -576459521,
  origin: "http://localhost",
  rp_id: "localhost",
  silent_authentication_enabled: false,
  timeout: 1200,
  token_binding_status: nil,
  trusted_attestation_types: [:none, :basic, :uncertain, :attca, :self],
  type: :attestation,
  user_verification: "preferred",
  verify_trust_root: true
}

# Decoded Client Data
client_data: %{
  "challenge" => <<70, 86, 81, 62, 234, 109, 239, 140, 123, 63, 220, 144, 15,
    203, 189, 151, 171, 128, 90, 251, 43, 189, 215, 68, 56, 67, 91, 233, 174,
    85, 230, 235>>,
  "clientExtensions" => %{},
  "hashAlgorithm" => "SHA-256",
  "origin" => "http://localhost",
  "type" => "webauthn.create"
}

Thanks to everyone who chimed in! :pray:

Also Liked

type1fool

type1fool

I should clarify that I’m not using Wax at the moment since I want to A) keep my dependencies minimal and B) understand WebAuthn by implementing it myself.

Once this is working for registration and login, I would like to open source the work as a LiveComponent for LiveView apps.

type1fool

type1fool

Ok, I poked around webauthn.io and found that it would only work in Safari if attestation was set to none. Problem solved I suppose, though I’m reading further on implications of this change.

Testing on my iPhone with Safari 15.4, somehow, navigator.credentials doesn’t exist. I’m baffled since webauth.io can register, and I see the call to navigator.credentials.create in the source JS. I do have Web Authentication API & Web Authentication Modern enabled in advanced settings, and it seems to have been supported since v13 (caniuse). This is weird.

Edit: Eureka!
It turns out Safari only allows navigator.credentials on https with no exception for localhost. Running my site over ngrok https, WebAuthn works! :beers:

al2o3cr

al2o3cr

I believe window.atob is not the right thing to use for this - the HTML specification describes what it does, and it isn’t “decode URL-safe base64”:

  1. If data contains a code point that is not one of

Where Next?

Popular in Questions Top

vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
Tee
can someone please explain to me how Enum.reduce works with maps
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID&lt;0.412.0&gt; terminating ** (Postgrex.Error) FATAL...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lists...
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
JulienCorb
I am trying to implement my new.html.eex file to create new posts on my website. new.html.eex: &lt;h1&gt;Create Post&lt;/h1&gt; &lt;%= ...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
New

Other popular topics Top

vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
johnnyicon
Hi all, I’ve just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I’m trying to use Postgres...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New
RisingFromAshes
I’ve read in another post that it may be possible with a router helper - but I couldn’t find an appropriate one, and tbh, I’m still just ...
New
komlanvi
Hi everyone, I was playing with phoenix liveView but I run into an issue. I have a form and want to validate each input text when the te...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
dogweather
I wrote this comment on r/haskell, and it’s not popular there. :wink: But I think I’m on to something… Haskell reminds me of Java, and e...
New
svb
Hi! Currently I want to submit a form by pressing the Enter key. However, since my input field is of type “textarea” this is just adds a...
New
sergio
Kind of like when jquery came out, it was super necessary. Existing drag and drop libraries have a bunch of baggage to support old browse...
New

We're in Beta

About us Mission Statement