1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Schnittstabil\Psr7\Csrf\Middlewares; |
4
|
|
|
|
5
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
6
|
|
|
use Psr\Http\Message\ResponseInterface; |
7
|
|
|
use Schnittstabil\Psr7\Csrf\RequestAttributesTrait; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* Middleware for accepting CSRF tokens sent by HTTP headers. |
11
|
|
|
*/ |
12
|
|
|
class AcceptHeaderToken |
13
|
|
|
{ |
14
|
|
|
use RequestAttributesTrait; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* Used to validate tokens. |
18
|
|
|
* |
19
|
|
|
* @var callable |
20
|
|
|
*/ |
21
|
|
|
protected $tokenValidator; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* Header field name. |
25
|
|
|
* |
26
|
|
|
* @var string |
27
|
|
|
*/ |
28
|
|
|
protected $headerName; |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* Create new AcceptHeaderToken middleware. |
32
|
|
|
* |
33
|
|
|
* @param callable $tokenValidator Used to validate tokens |
34
|
|
|
* @param string $headerName Header field name |
35
|
|
|
*/ |
36
|
|
|
public function __construct(callable $tokenValidator, $headerName = 'X-XSRF-TOKEN') |
37
|
|
|
{ |
38
|
|
|
$this->tokenValidator = $tokenValidator; |
39
|
|
|
$this->headerName = $headerName; |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* Invoke middleware. |
44
|
|
|
* |
45
|
|
|
* @param ServerRequestInterface $request request object |
46
|
|
|
* @param ResponseInterface $response response object |
47
|
|
|
* @param callable $next next middleware |
48
|
|
|
* |
49
|
|
|
* @return ResponseInterface response object |
50
|
|
|
*/ |
51
|
|
|
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next) |
52
|
|
|
{ |
53
|
|
|
$isValid = $request->getAttribute(self::$isValidAttribute, false); |
54
|
|
|
$violations = $request->getAttribute(self::$violationsAttribute, []); |
55
|
|
|
|
56
|
|
|
foreach ($request->getHeader($this->headerName) as $token) { |
57
|
|
|
$tokenViolations = call_user_func($this->tokenValidator, $token); |
58
|
|
|
|
59
|
|
|
if (count($tokenViolations) === 0) { |
60
|
|
|
$isValid = true; |
61
|
|
|
continue; |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
$violations = array_merge($violations, $tokenViolations); |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
return $next($request |
68
|
|
|
->withAttribute(self::$isValidAttribute, $isValid) |
69
|
|
|
->withAttribute(self::$violationsAttribute, $violations), $response); |
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
|