{"id":19275408,"url":"https://github.com/samyoul/u2f-php-server","last_synced_at":"2025-04-21T23:30:42.895Z","repository":{"id":45474663,"uuid":"76043532","full_name":"Samyoul/U2F-php-server","owner":"Samyoul","description":"Server-side handling of U2F registration and authentication for PHP","archived":false,"fork":false,"pushed_at":"2021-06-11T22:05:05.000Z","size":28,"stargazers_count":35,"open_issues_count":5,"forks_count":7,"subscribers_count":4,"default_branch":"master","last_synced_at":"2025-04-20T07:48:04.093Z","etag":null,"topics":["2fa","fido-u2f","php","u2f","u2f-php-server","u2f-registration"],"latest_commit_sha":null,"homepage":null,"language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"bsd-2-clause","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Samyoul.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2016-12-09T14:44:07.000Z","updated_at":"2024-10-05T01:02:55.000Z","dependencies_parsed_at":"2022-07-16T14:30:39.285Z","dependency_job_id":null,"html_url":"https://github.com/Samyoul/U2F-php-server","commit_stats":null,"previous_names":[],"tags_count":7,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Samyoul%2FU2F-php-server","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Samyoul%2FU2F-php-server/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Samyoul%2FU2F-php-server/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Samyoul%2FU2F-php-server/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Samyoul","download_url":"https://codeload.github.com/Samyoul/U2F-php-server/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":250150553,"owners_count":21383186,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["2fa","fido-u2f","php","u2f","u2f-php-server","u2f-registration"],"created_at":"2024-11-09T20:50:41.503Z","updated_at":"2025-04-21T23:30:42.656Z","avatar_url":"https://github.com/Samyoul.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"# U2F-php-server\n\n[![Latest Stable Version](https://img.shields.io/packagist/v/samyoul/u2f-php-server.svg?style=flat-square)](https://packagist.org/packages/samyoul/u2f-php-server)\n[![License](https://img.shields.io/badge/license-BSD_2_Clause-brightgreen.svg?style=flat-square)](LICENCE.md)\n\nServer-side handling of FIDO U2F registration and authentication for PHP.\n\nSecuring your online accounts and doing your bit to protect your data is extremely important and increasingly more so as hackers get more sophisticated.\nFIDO's U2F enables you to add a simple unobtrusive method of 2nd factor authentication, allowing users of your service and/or application to link a hardware key to their account.\n\n## The Family of U2F php Libraries\n\n**Base Library**\n\nhttps://github.com/Samyoul/U2F-php-server\n\n**Fido Test Suite (UTD)**\n\nhttps://github.com/Samyoul/U2F-php-UTD\n\n**Frameworks**\n\n*Laravel* https://github.com/Samyoul/U2F-Laravel-server\n\n*Yii* https://github.com/Samyoul/U2F-Yii-server\n\n*CodeIgniter* https://github.com/Samyoul/U2F-CodeIgniter-server\n\n\n## Contents\n\n1. [Installation](#installation)\n2. [Requirements](#requirements)\n    1. [OpenSSL](#openssl)\n    1. [Clientside Magic](#client-side-the-magic-javascript-bit-of-talking-with-a-usb-device)\n    1. [HTTPS and SSL](#https-and-ssl)\n3. [Terminology](#terminology)\n4. [Recommended Datastore Structure](#recommended-datastore-structure)\n5. [Process Workflow](#process-workflow)\n    1. [Registration Process Flow](#registration-process-flow)\n    1. [Authentication Process Flow](#authentication-process-flow)\n6. [Example Code](#example-code)\n    1. [Compatibility Check](#compatibility-code)\n    1. [Registration Code](#registration-code)\n    1. [Authentication Code](#authentication-code)\n7. [Frameworks](#frameworks)\n    1. [Laravel](#laravel-framework)\n    1. [Yii](#yii-framework)\n    1. [CodeIgniter](#codeigniter-framework)\n8. [Licence](#licence)\n9. [Credits](#credits)\n\n## Installation\n\n`composer require samyoul/u2f-php-server`\n\n## Requirements\n\nA few **things you need** to know before working with this:\n\n1. [**_OpenSSL_**](#openssl) You need at least OpenSSL 1.0.0 or higher.\n2. [**_Client-side Handling_**](#client-side) You need to be able to communicate with a some kind of device.\n3. [**_A HTTPS URL_**](#https-and-ssl) This is very important, without HTTPS U2F simply will not work.\n4. [**_A Datastore_**](#recommended-datastore-structure) You need some kind of datastore for all your U2F registered users (although if you have a system with user authentication I'm presuming you've got this one sorted).\n\n### OpenSSL\n\nThis repository requires OpenSSL 1.0.0 or higher. For further details on installing OpenSSL please refer to the php manual http://php.net/manual/en/openssl.installation.php .\n\nAlso see [Compatibility Code](#compatibility-code), to check if you have the correct version of OpenSSL installed, and are unsure how else to check.\n\n### Client-side (The magic JavaScript Bit of talking with a USB device)\n\nMy presumption is that if you are looking to add U2F authentication to a php system, then you'll probably are also looking for some client-side handling. You've got a U2F enabled USB device and you want to get the USB device speaking with the browser and then with your server running php.\n\n1. Google already have this bit sorted : https://github.com/google/u2f-ref-code/blob/master/u2f-gae-demo/war/js/u2f-api.js\n2. [Mastahyeti](https://github.com/mastahyeti) has created a repo dedicated to Google's JavaScript Client-side API : https://github.com/mastahyeti/u2f-api\n\n### HTTPS and SSL\n\nFor U2F to work your website/service must use a HTTPS URL. Without a HTTPS URL your code won't work, so get one for your localhost, get one for your production. https://letsencrypt.org/\nBasically encrypt everything.\n\n\n## Terminology\n\n**_HID_** : _Human Interface Device_, like A USB Device [like these things](https://www.google.co.uk/search?q=fido+usb+key\u0026safe=off\u0026tbm=isch)\n\n## Recommended Datastore Structure\n\nYou don't need to follow this structure exactly, but you will need to associate your Registration data with a user. You'll also need to store the key handle, public key and the certificate, counter isn't 100% essential but it makes your application more secure.\n\n\n|Name|Type|Description|\n|---|---|---|\n|id|integer primary key||\n|user_id|integer||\n|key_handle|varchar(255)||\n|public_key|varchar(255)||\n|certificate|text||\n|counter|integer||\n\nTODO the descriptions\n\n## Process Workflow\n\n### Registration Process Flow\n\n1. User navigates to a 2nd factor authentication page in your application.\n\n... TODO add the rest of the registration process flow ...\n\n### Authentication Process Flow\n\n1. User navigates to their login page as they usually would, submits username and password.\n1. Server received POST request authentication data, normal username + password validation occurs\n1. On successful authentication, the application checks 2nd factor authentication is required. We're going to presume it is, otherwise the user would just be logged in at this stage.\n1. Application gets the user's registered signatures from the application datastore: `$registrations`.\n1. Application gets its ID, usually the domain the application is accessible from: `$appId`\n1. Application makes a `U2F::makeAuthentication($registrations, $appId)` call, the method returns an array of `SignRequest` objects: `$authenticationRequest`.\n1. Application JSON encodes the array and passes the data to the view\n1. When the browser loads the page the JavaScript fires the `u2f.sign(authenticationRequest, function(data){ // Callback logic })` function\n1. The view will use JavaScript / Browser to poll the host machine's ports for a FIDO U2F device\n1. Once the HID has been found the JavaScript / Browser will send the sign request with data.\n1. The HID will prompt the user to authorise the sign request\n1. On success the HID returns authentication data\n1. The JavaScript receives the HID's returned data and passes it to the server\n1. The application takes the returned data passes it to the `U2F::authenticate($authenticationRequest, $registrations, $authenticationResponse)` method\n1. If the method returns a registration and doesn't throw an Exception, authentication is complete.\n1. Set the user's session, inform the user of the success, and redirect them.\n\n## Example Code\n\nFor a full working code example for this repository please see [the dedicated example repository](https://github.com/Samyoul/U2F-php-server-examples)\n\nYou can also install it with the following:\n\n```bash\n$ git clone https://github.com/Samyoul/U2F-php-server-examples.git\n$ cd u2f-php-server-examples\n$ composer install \n```\n\n\n1. [Compatibility Code](#compatibility-code)\n2. [Registration Code](#registration-code)\n    1. [Step 1: Starting](#registration-step-1)\n    1. [Step 2: Talking to the HID](#registration-step-2)\n    1. [Step 3: Validation \u0026 Storage](#registration-step-3)\n3. [Authentication Code]()\n    1. [Step 1: Starting]()\n    1. [Step 2: Talking to the HID]()\n    1. [Step 3: Validation]()\n\n---\n\n### Compatibility Code\n\nYou'll only ever need to use this method call once per installation and only in the context of debugging if the class is giving you unexpected errors. This method call will check your OpenSSL version and ensure it is at least 1.0.0 .\n\n```php\n\u003c?php\n\nrequire('vendor/autoload.php');\nuse Samyoul\\U2F\\U2FServer\\U2FServer as U2F;\n\nvar_dump(U2F::checkOpenSSLVersion());\n```\n\n---\n\n### Registration Code\n\n#### Registration Step 1:\n**Starting the registration process:**\n\nWe assume that user has successfully authenticated and wishes to register.\n\n```php\n\u003c?php\n\nrequire('vendor/autoload.php');\nuse Samyoul\\U2F\\U2FServer\\U2FServer as U2F;\n\nsession_start();\n\n// This can be anything, but usually easier if you choose your applications domain and top level domain.\n$appId = \"yourdomain.tld\";\n\n// Call the makeRegistration method, passing in the app ID\n$registrationData = U2F::makeRegistration($appId);\n\n// Store the request for later\n$_SESSION['registrationRequest'] = $registrationData['request'];\n\n// Extract the request and signatures, JSON encode them so we can give the data to our javaScript magic\n$jsRequest = json_encode($registrationData['request']);\n$jsSignatures = json_encode($registrationData['signatures']);\n\n// now pass the data to a fictitious view.\necho View::make('template/location/u2f-registration.html', compact(\"jsRequest\", \"jsSignatures\"));\n```\n\n#### Registration Step 2:\n**Client-side, Talking To The USB**\n\nNon-AJAX client-side registration of U2F key token. AJAX can of course be used in your application, but it is easier to demonstrate a linear process without AJAX and callbacks. \n\n```html\n\u003chtml\u003e\n\u003chead\u003e\n    \u003ctitle\u003eU2F Key Registration\u003c/title\u003e\n\u003c/head\u003e\n\u003cbody\u003e\n    \u003ch1\u003eU2F Registration\u003c/h1\u003e\n    \u003ch2\u003ePlease enter your FIDO U2F device into your computer's USB port. Then confirm registration on the device.\u003c/h2\u003e\n    \n    \u003cdiv style=\"display:none;\"\u003e\n        \u003cform id=\"u2f_submission\" method=\"post\" action=\"auth/u2f-registration/confirm\"\u003e\n            \u003cinput id=\"u2f_registration_response\" name=\"registration_response\" value=\"\" /\u003e\n        \u003c/form\u003e\n    \u003c/div\u003e\n    \n\u003cscript type=\"javascript\" src=\"https://raw.githubusercontent.com/google/u2f-ref-code/master/u2f-gae-demo/war/js/u2f-api.js\"\u003e\u003c/script\u003e\n\u003cscript\u003e\n    setTimeout(function() {\n    \n        // A magic JS function that talks to the USB device. This function will keep polling for the USB device until it finds one.\n        u2f.register([\u003c?php echo $jsRequest ?\u003e], \u003c?php echo $jsSignatures ?\u003e], function(data) {\n           \n            // Handle returning error data\n            if(data.errorCode \u0026\u0026 errorCode != 0) {\n                alert(\"registration failed with error: \" + data.errorCode);\n                // Or handle the error however you'd like. \n                \n                return;\n            }\n    \n            // On success process the data from USB device to send to the server\n            var registration_response = JSON.stringify(data);\n            \n            // Get the form items so we can send data back to the server\n            var form = document.getElementById('u2f_submission');\n            var response = document.getElementById('u2f_registration_response');\n            \n            // Fill and submit form.\n            response.value = JSON.stringify(registration_response);\n            form.submit();\n        });\n    }, 1000);\n\u003c/script\u003e\n\u003c/body\u003e\n\u003c/html\u003e\n```\n\n#### Registration Step 3:\n**Validation and Key Storage**\n\nThis is the last stage of registration. Validate the registration response data against the original request data.\n\n```php\n\u003c?php\n\nrequire('vendor/autoload.php');\nuse Samyoul\\U2F\\U2FServer\\U2FServer as U2F;\n\nsession_start();\n\n// Fictitious function representing getting the authenticated user object\n$user = getAuthenticatedUser();\n\ntry {\n    \n    // Validate the registration response against the registration request.\n    // The output are the credentials you need to store for U2F authentication.\n    $validatedRegistration = U2F::register(\n        $_SESSION['registrationRequest'],\n        json_decode($_POST['u2f_registration_response'])\n    );\n    \n    // Fictitious function representing the storing of the validated U2F registration data against the authenticated user. \n    $user-\u003estoreRegistration($validatedRegistration);\n    \n    // Then let your user know what happened\n    $userMessage = \"Success\";\n} catch( Exception $e ) {\n    $userMessage = \"We had an error: \". $e-\u003egetMessage();\n}\n\n//Fictitious view.\necho View::make('template/location/u2f-registration-result.html', compact('userMessage'));\n```\n\n---\n\n### Authentication Code\n\n#### Authentication Step 1:\n**Starting the authentication process:**\n\nWe assume that user has successfully authenticated and has previously registered to use FIDO U2F.\n\n```php\n\u003c?php\n    \nrequire('vendor/autoload.php');\nuse Samyoul\\U2F\\U2FServer\\U2FServer as U2F;\n\nsession_start();\n\n// Fictitious function representing getting the authenticated user object\n$user = getAuthenticatedUser();\n\n// Fictitious function, get U2F registrations associated with the user\n$registrations = $user-\u003eU2FRegistrations();\n\n// This can be anything, but usually easier if you choose your applications domain and top level domain.\n$appId = \"yourdomain.tld\";\n\n// Call the U2F makeAuthentication method, passing in the user's registration(s) and the app ID\n$authenticationRequest = U2F::makeAuthentication($registrations, $appId);\n\n// Store the request for later\n$_SESSION['authenticationRequest'] = $authenticationRequest;\n\n// now pass the data to a fictitious view.\necho View::make('template/location/u2f-authentication.html', compact(\"authenticationRequest\"));\n```\n\n#### Authentication Step 2:\n**Client-side, Talking To The USB**\n\nNon-AJAX client-side authentication of U2F key token. AJAX can of course be used in your application, but it is easier to demonstrate a linear process without AJAX and callbacks. \n\n\n```html\n\u003chtml\u003e\n\u003chead\u003e\n    \u003ctitle\u003eU2F Key Authentication\u003c/title\u003e\n\u003c/head\u003e\n\u003cbody\u003e\n    \u003ch1\u003eU2F Authentication\u003c/h1\u003e\n    \u003ch2\u003ePlease enter your FIDO U2F device into your computer's USB port. Then confirm authentication on the device.\u003c/h2\u003e\n    \n    \u003cdiv style=\"display:none;\"\u003e\n        \u003cform id=\"u2f_submission\" method=\"post\" action=\"auth/u2f-authentication/confirm\"\u003e\n            \u003cinput id=\"u2f_authentication_response\" name=\"authentication_response\" value=\"\" /\u003e\n        \u003c/form\u003e\n    \u003c/div\u003e\n\n    \u003cscript type=\"javascript\" src=\"https://raw.githubusercontent.com/google/u2f-ref-code/master/u2f-gae-demo/war/js/u2f-api.js\"\u003e\u003c/script\u003e\n    \u003cscript\u003e\n    setTimeout(function() {\n        \n        // Magic JavaScript talking to your HID\n        u2f.sign(\u003c?php echo $authenticationRequest; ?\u003e, function(data) {\n            \n            // Handle returning error data\n            if(data.errorCode \u0026\u0026 errorCode != 0) {\n                alert(\"Authentication failed with error: \" + data.errorCode);\n                // Or handle the error however you'd like. \n                \n                return;\n            }\n    \n            // On success process the data from USB device to send to the server\n            var authentication_response = JSON.stringify(data);\n            \n            // Get the form items so we can send data back to the server\n            var form = document.getElementById('u2f_submission');\n            var response = document.getElementById('u2f_authentication_response');\n            \n            // Fill and submit form.\n            response.value = JSON.stringify(authentication_response);\n            form.submit();\n        });\n    }, 1000);\n    \u003c/script\u003e\n\u003c/body\u003e\n\u003c/html\u003e\n```\n\n#### Authentication Step 3:\n**Validation**\n\nThis is the last stage of authentication. Validate the authentication response data against the original request data.\n\n```php\n\u003c?php\n\nrequire('vendor/autoload.php');\nuse Samyoul\\U2F\\U2FServer\\U2FServer as U2F;\n\nsession_start();\n\n// Fictitious function representing getting the authenticated user object\n$user = authenticatedUser();\n\n// Fictitious function, get U2F registrations associated with the user\n$registrations = $user-\u003eU2FRegistrations();\n\ntry {\n    \n    // Validate the authentication response against the registration request.\n    // The output are the credentials you need to store for U2F authentication.\n    $validatedAuthentication = U2F::authenticate(\n        $_SESSION['authenticationRequest'],\n        $registrations,\n        json_decode($_POST['u2f_authentication_response'])\n    );\n    \n    // Fictitious function representing the updating of the U2F token count integer. \n    $user-\u003eupdateU2FRegistrationCount($validatedAuthentication);\n    \n    // Then let your user know what happened\n    $userMessage = \"Success\";\n} catch( Exception $e ) {\n    $userMessage = \"We had an error: \". $e-\u003egetMessage();\n}\n\n//Fictitious view.\necho View::make('template/location/u2f-authentication-result.html', compact('userMessage'));\n```\n\n---\n\nAgain, if you want to just download some example code to play with just install the full working code examples written for this repository please see [the dedicated example repository](https://github.com/Samyoul/U2F-php-server-examples)\n\nYou can also install it with the following:\n\n```bash\n$ git clone https://github.com/Samyoul/U2F-php-server-examples.git\n$ cd u2f-php-server-examples\n$ composer install \n```\n\n## Frameworks\n\n### Laravel Framework\n\nSee the dedicated repository : https://github.com/Samyoul/U2F-Laravel-server\n\nInstallation:\n\n`composer require u2f-laravel-server`\n\n### Yii Framework\n\nSee the dedicated repository : https://github.com/Samyoul/U2F-Yii-server\n\nInstallation:\n\n`composer require u2f-yii-server`\n\n### CodeIgniter Framework\n\nSee the dedicated repository : https://github.com/Samyoul/U2F-CodeIgniter-server\n\nInstallation:\n\n`composer require u2f-codeigniter-server`\n\n### Can't see yours?\n\n**Your favourite php framework not in this list? Get coding and submit a pull request and get your framework extension included here.**\n\n## Licence\n\nThe repository is licensed under a BSD license. [Read details here](https://github.com/Samyoul/U2F-php-server/blob/master/LICENCE.md)\n\n## Credits\n\nThis repo was originally based on the Yubico php-u2flib-server https://github.com/Yubico/php-u2flib-server\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsamyoul%2Fu2f-php-server","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsamyoul%2Fu2f-php-server","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsamyoul%2Fu2f-php-server/lists"}