mirror of
https://github.com/getnamingo/registry.git
synced 2025-06-29 07:33:27 +02:00
More work on 2FA and WebAuthn
This commit is contained in:
parent
6466545c90
commit
2b6bdc71e9
3 changed files with 125 additions and 75 deletions
|
@ -26,6 +26,10 @@ class ProfileController extends Controller
|
|||
$username = $_SESSION['auth_username'];
|
||||
$email = $_SESSION['auth_email'];
|
||||
$status = $_SESSION['auth_status'];
|
||||
$tfa = new \RobThree\Auth\TwoFactorAuth('Namingo');
|
||||
$secret = $tfa->createSecret();
|
||||
$qrcodeDataUri = $tfa->getQRCodeImageAsDataUri($email, $secret);
|
||||
|
||||
if ($status == 0) {
|
||||
$status = "Confirmed";
|
||||
} else {
|
||||
|
@ -38,51 +42,77 @@ class ProfileController extends Controller
|
|||
$role = "Unknown";
|
||||
}
|
||||
|
||||
return view($response,'admin/profile/profile.twig',['email' => $email, 'username' => $username, 'status' => $status, 'role' => $role]);
|
||||
global $container;
|
||||
$csrfName = $container->get('csrf')->getTokenName();
|
||||
$csrfValue = $container->get('csrf')->getTokenValue();
|
||||
|
||||
return view($response,'admin/profile/profile.twig',['email' => $email, 'username' => $username, 'status' => $status, 'role' => $role, 'qrcodeDataUri' => $qrcodeDataUri, 'secret' => $secret, 'csrf_name' => $csrfName, 'csrf_value' => $csrfValue]);
|
||||
}
|
||||
|
||||
public function getRegistrationChallenge(Request $request, Response $response)
|
||||
{
|
||||
$username = $_SESSION['auth_username'];
|
||||
$userName = $_SESSION['auth_username'];
|
||||
$userEmail = $_SESSION['auth_email'];
|
||||
$userId = $_SESSION['auth_user_id'];
|
||||
|
||||
$challenge = $this->webAuthn->prepareChallengeForRegistration($username, $userEmail);
|
||||
$_SESSION['webauthn_challenge'] = $challenge; // Store the challenge in the session
|
||||
// Convert the user ID to a hexadecimal string
|
||||
$userIdHex = dechex($userId);
|
||||
// Pad with a leading zero if the length is odd
|
||||
if (strlen($userIdHex) % 2 !== 0) {
|
||||
$userIdHex = '0' . $userIdHex;
|
||||
}
|
||||
|
||||
$response->getBody()->write(json_encode($challenge));
|
||||
// Convert the padded hexadecimal string to binary, then encode in Base64
|
||||
$userIdBin = hex2bin($userIdHex);
|
||||
$userIdBase64 = base64_encode($userIdBin);
|
||||
|
||||
// Generate the create arguments using the WebAuthn library
|
||||
$createArgs = $this->webAuthn->getCreateArgs($userIdBase64, $userName, $userEmail, 60 * 4, 0, 'required', null);
|
||||
|
||||
// Encode the challenge in Base64
|
||||
$base64Challenge = base64_encode($this->webAuthn->getChallenge());
|
||||
|
||||
// Set the challenge and user ID in the createArgs object
|
||||
$createArgs->publicKey->challenge = $base64Challenge;
|
||||
$createArgs->publicKey->user->id = $userIdBase64;
|
||||
|
||||
// Store the challenge in the session
|
||||
$_SESSION['webauthn_challenge'] = $base64Challenge;
|
||||
|
||||
// Send the modified $createArgs to the client
|
||||
$response->getBody()->write(json_encode($createArgs));
|
||||
return $response->withHeader('Content-Type', 'application/json');
|
||||
}
|
||||
|
||||
public function verifyRegistration(Request $request, Response $response)
|
||||
{
|
||||
$data = json_decode($request->getBody()->getContents(), true);
|
||||
$data = json_decode($request->getBody()->getContents());
|
||||
|
||||
try {
|
||||
$credential = $this->webAuthn->processCreate($data, $_SESSION['webauthn_challenge']);
|
||||
unset($_SESSION['webauthn_challenge']);
|
||||
// Decode the incoming data
|
||||
$clientDataJSON = base64_decode($data->response->clientDataJSON);
|
||||
$attestationObject = base64_decode($data->response->attestationObject);
|
||||
|
||||
// Retrieve the challenge from the session
|
||||
$challenge = $_SESSION['webauthn_challenge'];
|
||||
|
||||
// Process the WebAuthn response
|
||||
$credential = $this->webAuthn->processCreate($clientDataJSON, $attestationObject, $challenge, true, true, false);
|
||||
|
||||
// Store the credential data in the database
|
||||
$db = $this->container->get('db');
|
||||
$db->insert(
|
||||
'users_webauthn',
|
||||
[
|
||||
'user_id' => $_SESSION['auth_user_id'],
|
||||
'credential_id' => base64_encode($credential->credentialId), // Binary data encoded in Base64
|
||||
'public_key' => $credential->publicKey, // Text data
|
||||
'attestation_object' => base64_encode($credential->attestationObject), // Binary data encoded in Base64
|
||||
'sign_count' => $credential->signCount // Integer
|
||||
]
|
||||
);
|
||||
|
||||
try {
|
||||
$db->insert(
|
||||
'users_webauthn',
|
||||
[
|
||||
'user_id' => $_SESSION['auth_user_id'],
|
||||
'credential_id' => $credential->getCredentialId(), // Binary data
|
||||
'public_key' => $credential->getPublicKey(), // Text data
|
||||
'attestation_object' => $credential->getAttestationObject(), // Binary data
|
||||
'sign_count' => $credential->getSignCount() // Integer
|
||||
]
|
||||
);
|
||||
} catch (IntegrityConstraintViolationException $e) {
|
||||
// Handle the case where the insert operation violates a constraint
|
||||
// For example, a duplicate credential_id
|
||||
throw new \Exception('Could not store WebAuthn credentials: ' . $e->getMessage());
|
||||
} catch (Error $e) {
|
||||
// Handle other database errors
|
||||
throw new \Exception('Database error: ' . $e->getMessage());
|
||||
}
|
||||
|
||||
// Send success response
|
||||
$response->getBody()->write(json_encode(['success' => true]));
|
||||
return $response->withHeader('Content-Type', 'application/json');
|
||||
} catch (\Exception $e) {
|
||||
|
|
|
@ -37,7 +37,8 @@
|
|||
"league/iso3166": "^4.3",
|
||||
"stripe/stripe-php": "^13.3",
|
||||
"robthree/twofactorauth": "^2.1",
|
||||
"lbuchs/webauthn": "^2.1"
|
||||
"lbuchs/webauthn": "^2.1",
|
||||
"bacon/bacon-qr-code": "^2.0"
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
|
|
|
@ -101,12 +101,23 @@
|
|||
<p>Set up 2FA for additional security. Scan the QR code with your authentication app and enter the provided code below to verify.</p>
|
||||
<!-- QR Code Placeholder -->
|
||||
<div class="mb-3">
|
||||
<img src="path/to/qr-code.png" alt="2FA QR Code" class="img-fluid">
|
||||
<img src="{{ qrcodeDataUri }}" alt="2FA QR Code" class="img-fluid">
|
||||
</div>
|
||||
<!-- Secret for Manual Entry -->
|
||||
<div class="mb-3">
|
||||
<p class="font-weight-bold">Manual Entry Secret</p>
|
||||
<code>{{ secret|split(4)|join(' ') }}</code>
|
||||
<small class="form-text text-muted">
|
||||
If you're unable to scan the QR code, enter this secret manually into your authentication app. The secret is case-sensitive and should be entered exactly as shown.
|
||||
</small>
|
||||
</div>
|
||||
<!-- Verification Code Input -->
|
||||
<div class="mb-3">
|
||||
<label for="verificationCode" class="form-label">Verification Code</label>
|
||||
<input type="text" class="form-control" id="verificationCode" placeholder="Enter code">
|
||||
<small class="form-text text-muted">
|
||||
Enter the code generated by your authentication app. This code verifies that your 2FA setup is working correctly. Once entered, click 'Save 2FA Settings' to activate two-factor authentication for your account.
|
||||
</small>
|
||||
</div>
|
||||
<!-- Save Button -->
|
||||
<button type="button" class="btn btn-primary">Save 2FA Settings</button>
|
||||
|
@ -160,49 +171,57 @@
|
|||
document.addEventListener('DOMContentLoaded', function() {
|
||||
const connectButton = document.getElementById('connectWebAuthnButton');
|
||||
|
||||
connectButton.addEventListener('click', function() {
|
||||
// Step 1: Get the registration challenge from the server
|
||||
fetch('/webauthn/register/challenge')
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
// Step 2: Call WebAuthn API to create credentials
|
||||
return navigator.credentials.create({
|
||||
publicKey: data
|
||||
});
|
||||
})
|
||||
.then(credentials => {
|
||||
// Step 3: Send the credentials back to the server for verification
|
||||
const publicKeyCredential = {
|
||||
id: credentials.id,
|
||||
rawId: btoa(String.fromCharCode.apply(null, new Uint8Array(credentials.rawId))),
|
||||
type: credentials.type,
|
||||
response: {
|
||||
attestationObject: btoa(String.fromCharCode.apply(null, new Uint8Array(credentials.response.attestationObject))),
|
||||
clientDataJSON: btoa(String.fromCharCode.apply(null, new Uint8Array(credentials.response.clientDataJSON)))
|
||||
}
|
||||
};
|
||||
connectButton.addEventListener('click', async function() {
|
||||
try {
|
||||
// Step 1: Get the registration challenge from the server
|
||||
const response = await fetch('/webauthn/register/challenge');
|
||||
const data = await response.json();
|
||||
|
||||
return fetch('/webauthn/register/verify', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify(publicKeyCredential)
|
||||
});
|
||||
})
|
||||
.then(response => {
|
||||
if(response.ok) {
|
||||
// Handle successful registration, e.g., update the UI
|
||||
alert('Registration successful!');
|
||||
window.location.reload();
|
||||
} else {
|
||||
// Handle registration error
|
||||
alert('Registration failed: ' + (data.error || 'Unknown error'));
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Error during WebAuthn registration:', error);
|
||||
// Decode the challenge and user ID from Base64 to Uint8Array
|
||||
const challenge = Uint8Array.from(atob(data.publicKey.challenge), c => c.charCodeAt(0));
|
||||
const userId = Uint8Array.from(atob(data.publicKey.user.id), c => c.charCodeAt(0));
|
||||
|
||||
// Modify the data object to use the decoded challenge and user ID
|
||||
data.publicKey.challenge = challenge;
|
||||
data.publicKey.user.id = userId;
|
||||
|
||||
// Step 2: Call WebAuthn API to create credentials
|
||||
const credentials = await navigator.credentials.create(data);
|
||||
|
||||
// Prepare credentials response
|
||||
const publicKeyCredential = {
|
||||
id: credentials.id,
|
||||
rawId: btoa(String.fromCharCode.apply(null, new Uint8Array(credentials.rawId))),
|
||||
type: credentials.type,
|
||||
response: {
|
||||
attestationObject: btoa(String.fromCharCode.apply(null, new Uint8Array(credentials.response.attestationObject))),
|
||||
clientDataJSON: btoa(String.fromCharCode.apply(null, new Uint8Array(credentials.response.clientDataJSON)))
|
||||
},
|
||||
// Include CSRF tokens in the payload
|
||||
csrf_name: '{{ csrf_name }}',
|
||||
csrf_value: '{{ csrf_value }}'
|
||||
};
|
||||
|
||||
// Step 3: Send the credentials back to the server for verification
|
||||
const verificationResponse = await fetch('/webauthn/register/verify', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify(publicKeyCredential)
|
||||
});
|
||||
|
||||
if(verificationResponse.ok) {
|
||||
alert('Registration successful!');
|
||||
window.location.reload();
|
||||
} else {
|
||||
const errorData = await verificationResponse.json();
|
||||
alert('Registration failed: ' + (errorData.error || 'Unknown error'));
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error during WebAuthn registration:', error);
|
||||
alert('Error during registration: ' + error.message);
|
||||
}
|
||||
});
|
||||
});
|
||||
</script>
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue