-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathAuthenticationMiddleware.php
More file actions
75 lines (63 loc) · 2.07 KB
/
AuthenticationMiddleware.php
File metadata and controls
75 lines (63 loc) · 2.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
<?php
namespace PhpMiddleware\HttpAuthentication;
use PhpMiddleware\HttpAuthentication\Exception\MissingAuthorizationResult;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
final class AuthenticationMiddleware implements AuthorizationResultProviderInterface
{
/**
* @var AuthorizationServiceInterface
*/
protected $service;
/**
* @var AuthorizationResultInterface
*/
private $authorizationResult;
/**
* @param AuthorizationServiceInterface $service
*/
public function __construct(AuthorizationServiceInterface $service)
{
$this->service = $service;
}
/**
* @param ServerRequestInterface $request
* @param ResponseInterface $response
* @param callable $out
*
* @return ResponseInterface
*/
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $out)
{
$this->authorizationResult = $this->service->authorize($request);
if (true === $this->authorizationResult->isAuthorized()) {
$requestWithResult = $request->withAttribute(AuthorizationResultInterface::class, $this->authorizationResult);
return $out($requestWithResult, $response);
}
$header = $this->buildWwwAuthenticateHeader($this->authorizationResult);
return $response
->withStatus(401)
->withHeader('WWW-Authenticate', $header);
}
/**
* @return AuthorizationResultInterface
*
* @throws MissingAuthorizationResult
*/
public function getAuthorizationResult()
{
if ($this->authorizationResult === null) {
throw new MissingAuthorizationResult('Middleware must be called first');
}
return $this->authorizationResult;
}
/**
* @param AuthorizationResultInterface $result
*
* @return string
*/
private function buildWwwAuthenticateHeader(AuthorizationResultInterface $result)
{
return Util::buildHeader($result->getScheme(), $result->getChallenge());
}
}