# PHP Software Libraries (FIDO2)

**For details of the source libraries see:**

* [Server side repo](https://github.com/SAFETECHio/FIDO2_SERVER_Libraries)
* [Client side repo](https://github.com/SAFETECHio/FIDO2_CLIENT_Libraries)

## Example <a href="#safetechio-php-fido2-example" id="safetechio-php-fido2-example"></a>

{% hint style="info" %}
**SAFETECHio PHP FIDO2 / WebAuthn Example**
{% endhint %}

<figure><img src="https://3973835675-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FYeTaNjAJ9cNjqtDmTkU1%2Fuploads%2Fjd3XDGtFXFqXCNpfDeUg%2FSAFETECHio%20PHP%20FIDO2%20Example.png?alt=media&#x26;token=4bfa15e5-da5d-4da5-86b6-a3a68b567473" alt=""><figcaption></figcaption></figure>

## Getting Started <a href="#getting-started" id="getting-started"></a>

If you don't have access to a running configured php server no problem you can use the docker container provided.

Open a new terminal window and navigate to the root director of this repo on your machine and enter

```
docker-composer up
```

Open another separate terminal and enter the following commands

```
docker exec -it fido2-example /bin/bash
cd app
composer install
npm install
npm run build
```

After the installation of the packages dependencies has been completed navigate to the following URL

```
http://localhost:8082/dist/
```

## Browser Compatibility <a href="#browser-compatibility" id="browser-compatibility"></a>

To get the latest details of which version of which browsers offer support for WebAuthn please visit [Can I Use WebAuthn](https://caniuse.com/#search=webauthn). As of writing (2019-06-28) the following browsers have support:

<figure><img src="https://3973835675-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FYeTaNjAJ9cNjqtDmTkU1%2Fuploads%2FFlWGr1ffs5j9txMUgYql%2Fcan-I-use-webauthn.png?alt=media&#x26;token=0a5cc4f8-e1d0-4700-ab84-87eaf28a7bef" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}

### Microsoft Edge <a href="#microsoft-edge" id="microsoft-edge"></a>

Edge has support in version 18 and higher. However Edge is not updated independently of the operating system, this means that in order to update your version of Edge you will need to update your version of Windows 10.

Updating Windows 10 to the latest version may require a few steps, first check your computer has all pending updates installed by following [the instructions here](https://support.microsoft.com/en-gb/help/4027667/windows-10-update).

If after all available updates have been installed and your version of Edge is still lower than 17 you will need to manually update your OS. The [latest update for Windows 10 can be found here](https://www.microsoft.com/en-us/software-download/windows10).

This process may take a long time, so it may be easier to use a more popular browser that does support the latest in web security ;).
{% endhint %}

## Server Side FIDO2/WebAuthn PHP Library <a href="#php-fido2-webauthn-server" id="php-fido2-webauthn-server"></a>

### WebAuthn <a href="#webauthn" id="webauthn"></a>

For more detailed example of the library please see the [dedicated repo](https://github.com/SAFETECHio/PHP-FIDO2-Example).

### WebAuthn Initialize <a href="#webauthn-initialize" id="webauthn-initialize"></a>

```php
<?php
// Initialise

use SAFETECHio\FIDO2\WebAuthn;

$WebAConfig = new WebAuthn\WebAuthnConfig(
    "Example Name",
    "example.com",
    "https://login.example.com",          // Optional
    "https://example.com/images/logo.png" // Optional
); 
$WebA = new WebAuthn\WebAuthnServer($WebAConfig);
```

### WebAuthn Register User <a href="#webauthn-register-user" id="webauthn-register-user"></a>

#### **WebAuthn Begin Registration**

```php
<?php
// Begin Registration

use SAFETECHio\FIDO2\WebAuthn;

// create or find the registering user from your data store
$user = DB\User::FindOrCreate();  

/** @var $WebA WebAuthn\WebAuthnServer */
list($options, $sessionData) = $WebA->BeginRegistration($user)->Make();

// sessionData should be saved in the registration session
session_start();
$_SESSION['registration_session'] = $sessionData;

echo json_encode($options);
// respond with the options
// options->publicKey contains the registration options
```

#### **WebAuthn Complete Registration**

```php
<?php
// Complete Registration

use SAFETECHio\FIDO2\WebAuthn;

// find the registering user from your data store
$user = DB\User::Find();  

// Get the session data stored in the beginRegistration step
session_start();
$sessionData = $_SESSION['registration_session'];

// Call the WebAuthn->completeRegistration() func
/** @var $WebA WebAuthn\WebAuthnServer */
$credential = $WebA->completeRegistration($user, $sessionData, $jsonResponse);

// If creation was successful, store the credential object
$user->Credentials()->Create($credential);

// Destroy the registration session
unset($_SESSION['registration_session']);

// Respond with a success message
echo json_encode("Registration Success");
```

### WebAuthn Authenticate User <a href="#webauthn-authenticate-user" id="webauthn-authenticate-user"></a>

#### **WebAuthn Begin Authentication**

```php
<?php
// Begin Authentication

use SAFETECHio\FIDO2\WebAuthn;

// find the registering user from your data store
$user = DB\User::Find();

/** @var $WebA WebAuthn\WebAuthnServer */
list($options, $sessionData) = $WebA->beginAuthentication($user);

// sessionData should be saved in the authentication session
session_start();
$_SESSION['authentication_session'] = $sessionData;

echo json_encode($options);
// respond with the options
// options->publicKey contains the registration options
```

#### **WebAuthn Complete Authentication**

```php
<?php
// Complete Authentication

use SAFETECHio\FIDO2\WebAuthn;

// find the registering user from your data store
$user = DB\User::Find();

// Get the authentication session data stored in the beginAuthentication step
session_start();
$sessionData = $_SESSION['authentication_session'];

/** @var $WebA WebAuthn\WebAuthnServer */
$credential = $WebA->completeAuthentication($user, $sessionData);

// Destroy the registration session
unset($_SESSION['authentication_session']);

// Respond with a success message
echo json_encode("Registration Success");
```

### Docker <a href="#docker" id="docker"></a>

To get set up with docker.

```
docker-composer up
```

In a separate terminal

```
docker exec -it fido2-app /bin/bash
```

## Client Side FIDO2/WebAuthn JS Library <a href="#fido2-webauthn-client-side-js-library" id="fido2-webauthn-client-side-js-library"></a>

For more advanced details of how to use this library please see the [php full stack example](https://github.com/SAFETECHio/PHP-FIDO2-Example).

### Installation <a href="#installation" id="installation"></a>

`npm install SAFETECHio/FIDO2_CLIENT_Libraries`

### Example Use <a href="#example-use" id="example-use"></a>

#### **The JS**

```javascript
import {SAFETECHioWebAuthn, SAFETECHioWebAuthnConfig} from 'fido2_clientside';

let config = new SAFETECHioWebAuthnConfig();
config.registerBeginEndpoint += "../backend/RegisterBegin.php?username=";
config.registerCompleteEndpoint += "../backend/RegisterComplete.php?username=";
config.authenticateBeginEndpoint += "../backend/AuthenticateBegin.php?username=";
config.authenticateCompleteEndpoint += "../backend/AuthenticationComplete.php?username=";
config.usernameInputID = "#email";
config.giveErrorAlert = true;
config.giveSuccessAlert = true;

let SafeTechWebAuthn = new SAFETECHioWebAuthn(config);

export {config, SafeTechWebAuthn};
```

#### **The HTML**

```html
<!DOCTYPE html>
<html>

<head>
    <title>SAFETECHio FIDO2 Example</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>

<body>

<div class="container">
    <div class="row">
        <div class="col-md-2">
            <label for="email" class="col-12 col-form-label">Email :</label>
        </div>
        <div class="col-md-6">
            <input class="form-control" type="text" name="username" id="email" placeholder="i.e. name@example.com">
        </div>
        <div class="col-md-2">
            <button class="btn btn-primary btn-block" onclick="tech.SafeTechWebAuthn.registerUser()">Register</button>
        </div>
        <div class="col-md-2">
            <button class="btn btn-success btn-block"  onclick="tech.SafeTechWebAuthn.authenticateUser()">Authenticate</button>
        </div>
    </div>
</div>

<script src="main.js"></script>

</body>
</html>
```
