Skip to content

Instantly share code, notes, and snippets.

@code-boxx
Last active October 11, 2023 23:47
Show Gist options
  • Save code-boxx/550bce9510a4319d7537c9d2076bbaaf to your computer and use it in GitHub Desktop.
Save code-boxx/550bce9510a4319d7537c9d2076bbaaf to your computer and use it in GitHub Desktop.
Simple PHP Web Authn Example

SIMPLE PHP WEBAUTHN

https://code-boxx.com/simple-php-webauthn/

NOTES

  1. Change $rp to your own in 3-init.php.
  2. Run composer require lbuchs/webauthn to download the PHP Web Authn Library

LICENSE

Copyright by Code Boxx

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

<!DOCTYPE html>
<html>
<head>
<title>PHP WebAuthn Demo</title>
<script src="2-demo.js"></script>
</head>
<body>
<button onclick="register.a()">Register</button>
<button onclick="validate.a()">Validate</button>
</body>
</html>
// (A) HELPER FUNCTIONS
var helper = {
// (A1) ARRAY BUFFER TO BASE 64
atb : b => {
let u = new Uint8Array(b), s = "";
for (let i=0; i<u.byteLength; i++) { s += String.fromCharCode(u[i]); }
return btoa(s);
},
// (A2) BASE 64 TO ARRAY BUFFER
bta : o => {
let pre = "=?BINARY?B?", suf = "?=";
for (let k in o) { if (typeof o[k] == "string") {
let s = o[k];
if (s.substring(0, pre.length)==pre && s.substring(s.length - suf.length)==suf) {
let b = window.atob(s.substring(pre.length, s.length - suf.length)),
u = new Uint8Array(b.length);
for (let i=0; i<b.length; i++) { u[i] = b.charCodeAt(i); }
o[k] = u.buffer;
}
} else { helper.bta(o[k]); }}
},
// (A3) AJAX FETCH
ajax : (url, data, after) => {
let form = new FormData();
for (let [k,v] of Object.entries(data)) { form.append(k,v); }
fetch(url, { method: "POST", body: form })
.then(res => res.text())
.then(res => after(res))
.catch(err => { alert("ERROR!"); console.error(err); });
}
};
// (B) REGISTRATION
var register = {
// (B1) CREATE CREDENTIALS
a : () => helper.ajax("4-register.php", {
phase : "a"
}, async (res) => {
try {
res = JSON.parse(res);
helper.bta(res);
register.b(await navigator.credentials.create(res));
} catch (e) { alert(res); console.error(e); }
}),
// (B2) SEND CREDENTIALS TO SERVER
b : cred => helper.ajax("4-register.php", {
phase : "b",
transport : cred.response.getTransports ? cred.response.getTransports() : null,
client : cred.response.clientDataJSON ? helper.atb(cred.response.clientDataJSON) : null,
attest : cred.response.attestationObject ? helper.atb(cred.response.attestationObject) : null
}, res => alert(res))
};
// (C) VALIDATION
var validate = {
// (C1) GET CREDENTIALS
a : () => helper.ajax("5-validate.php", {
phase : "a"
}, async (res) => {
try {
res = JSON.parse(res);
helper.bta(res);
validate.b(await navigator.credentials.get(res));
} catch (e) { alert(res); console.error(e); }
}),
// (C2) SEND TO SERVER & VALIDATE
b : cred => helper.ajax("5-validate.php", {
phase : "b",
id : cred.rawId ? helper.atb(cred.rawId) : null,
client : cred.response.clientDataJSON ? helper.atb(cred.response.clientDataJSON) : null,
auth : cred.response.authenticatorData ? helper.atb(cred.response.authenticatorData) : null,
sig : cred.response.signature ? helper.atb(cred.response.signature) : null,
user : cred.response.userHandle ? helper.atb(cred.response.userHandle) : null
}, res => alert(res))
};
<?php
// (A) RELYING PARTY - CHANGE TO YOUR OWN!
$rp = [
"name" => "Code Boxx",
"id" => "localhost"
];
// (B) DUMMY USER
$user = [
"id" => "12345678",
"name" => "[email protected]",
"display" => "Jon Doe"
];
$saveto = "user.txt";
// (C) START SESSION & LOAD WEBAUTHN LIBRARY
session_start();
require "vendor/autoload.php";
$WebAuthn = new lbuchs\WebAuthn\WebAuthn($rp["name"], $rp["id"]);
<?php
// (A) INIT & CHECK
require "3-init.php";
if (file_exists($saveto)) { exit("User already registered"); }
switch ($_POST["phase"]) {
// (B) REGISTRATION PART 1 - GET ARGUMENTS
case "a":
$args = $WebAuthn->getCreateArgs(
\hex2bin($user["id"]), $user["name"], $user["display"],
30, false, true
);
$_SESSION["challenge"] = ($WebAuthn->getChallenge())->getBinaryString();
echo json_encode($args);
break;
// (C) REGISTRATION PART 2 - SAVE USER CREDENTIAL
// should be saved in database, but we save into a file instead
case "b":
// (C1) VALIDATE & PROCESS
try {
$data = $WebAuthn->processCreate(
base64_decode($_POST["client"]),
base64_decode($_POST["attest"]),
$_SESSION["challenge"],
true, true, false
);
} catch (Exception $ex) { print_r($ex); exit; }
// (C2) SAVE
file_put_contents($saveto, serialize($data));
echo "OK";
break;
}
<?php
// (A) INIT & CHECK
require "3-init.php";
if (!file_exists($saveto)) { exit("User is not registered"); }
$saved = unserialize(file_get_contents("user.txt"));
switch ($_POST["phase"]) {
// (B) VALIDATION PART 1 - GET ARGUMENTS
case "a":
$args = $WebAuthn->getGetArgs([$saved->credentialId], 30);
$_SESSION["challenge"] = ($WebAuthn->getChallenge())->getBinaryString();
echo json_encode($args);
break;
// (C) VALIDATION PART 2 - CHECKS & PROCESS
case "b":
$id = base64_decode($_POST["id"]);
if ($saved->credentialId !== $id) { exit("Invalid credentials"); }
try {
$WebAuthn->processGet(
base64_decode($_POST["client"]),
base64_decode($_POST["auth"]),
base64_decode($_POST["sig"]),
$saved->credentialPublicKey,
$_SESSION["challenge"]
);
echo "OK";
// DO WHATEVER IS REQUIRED AFTER VALIDATION
} catch (Exception $ex) { print_r($ex); exit; }
break;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment