|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Vectorface\SnappyRouter\Plugin\Authentication; |
|
4
|
|
|
|
|
5
|
|
|
use Vectorface\SnappyRouter\Exception\UnauthorizedException; |
|
6
|
|
|
use Vectorface\SnappyRouter\Handler\AbstractHandler; |
|
7
|
|
|
|
|
8
|
|
|
/** |
|
9
|
|
|
* A plugin to make use of PHP's built-in Auth support to provide HTTP/Basic authentication. |
|
10
|
|
|
* |
|
11
|
|
|
* Note: This class expects the AuthMechanism DI key set to an AuthenticatorInterface instance. |
|
12
|
|
|
* |
|
13
|
|
|
* @copyright Copyright (c) 2014, VectorFace, Inc. |
|
14
|
|
|
* @author J. Anderson <[email protected]> |
|
15
|
|
|
* @author Dan Bruce <[email protected]> |
|
16
|
|
|
*/ |
|
17
|
|
|
class HttpBasicAuthenticationPlugin extends AbstractAuthenticationPlugin |
|
18
|
|
|
{ |
|
19
|
|
|
/** The authentication realm, usually presented to the user in a |
|
20
|
|
|
username/password dialog box. */ |
|
21
|
|
|
private $realm = "Authentication Required"; |
|
22
|
|
|
|
|
23
|
|
|
/** |
|
24
|
|
|
* Create a new HTTP/Basic Authentication plugin. |
|
25
|
|
|
* |
|
26
|
|
|
* @param array $options An associative array of options. Supports AuthMechanism and realm options. |
|
27
|
|
|
*/ |
|
28
|
1 |
|
public function __construct($options) |
|
29
|
|
|
{ |
|
30
|
1 |
|
parent::__construct($options); |
|
31
|
|
|
|
|
32
|
1 |
|
if (!empty($options['realm'])) { |
|
33
|
1 |
|
$this->realm = $options['realm']; |
|
34
|
1 |
|
} |
|
35
|
1 |
|
} |
|
36
|
|
|
|
|
37
|
|
|
/** |
|
38
|
|
|
* Invoked directly after the router decides which handler will be used. |
|
39
|
|
|
* @param AbstractHandler $handler The handler selected by the router. |
|
40
|
|
|
*/ |
|
41
|
1 |
|
public function afterHandlerSelected(AbstractHandler $handler) |
|
42
|
|
|
{ |
|
43
|
|
|
try { |
|
44
|
1 |
|
parent::afterHandlerSelected($handler); |
|
45
|
1 |
|
} catch (UnauthorizedException $e) { |
|
46
|
1 |
|
@header(sprintf('WWW-Authenticate: Basic realm="%s"', $this->realm)); |
|
|
|
|
|
|
47
|
1 |
|
throw $e; |
|
48
|
|
|
} |
|
49
|
1 |
|
} |
|
50
|
|
|
|
|
51
|
|
|
/** |
|
52
|
|
|
* Extract credentials from the request, PHP's PHP_AUTH_(USER|PW) server variables in this case. |
|
53
|
|
|
* |
|
54
|
|
|
* @return mixed An array of credentials; A username and password pair, or false if credentials aren't available |
|
55
|
|
|
*/ |
|
56
|
1 |
|
public function getCredentials() |
|
|
|
|
|
|
57
|
|
|
{ |
|
58
|
1 |
|
if (isset($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'])) { |
|
59
|
1 |
|
return array($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']); |
|
60
|
|
|
} |
|
61
|
1 |
|
return false; |
|
62
|
|
|
} |
|
63
|
|
|
} |
|
64
|
|
|
|
If you suppress an error, we recommend checking for the error condition explicitly: