我不久前使用 Slim 2 创建了一个应用程序,我正在尝试添加 Angular。到目前为止一切顺利,但我不能再使用我正在使用的 CSRF 保护,因为 Angular 正在处理我所有的发布请求。下面是我工作的中间件之前。
<?php
namespace Cache\Middleware;
use Exception;
use Slim\Middleware;
class CsrfMiddleware extends Middleware {
protected $key;
public function call() {
$this->key = $this->app->config->get('csrf.key');
$this->app->hook('slim.before', [$this, 'check']);
$this->next->call();
}
public function check() {
if (!isset($_SESSION[$this->key])) {
$_SESSION[$this->key] = $this->app->hash->hash($this->app->randomlib->generateString(128));
}
$token = $_SESSION[$this->key];
if (in_array($this->app->request()->getMethod(), ['POST', 'PUT', 'DELETE'])) {
$submittedToken = $this->app->request()->post($this->key) ?: '';
if (!$this->app->hash->hashCheck($token, $submittedToken)) {
throw new Exception('CSRF token mismatch');
}
}
$this->app->view()->appendData([
'csrf_key' => $this->key,
'csrf_token' => $token
]);
}
}
我知道 Angular 会自动查找名为 XSRF-TOKEN 的令牌并将其作为 X-XSRF-TOKEN 添加到标题中。如何修改下面的中间件以写入、读取和比较正确的值。
编辑:
再次查看此内容并检查纤薄文档后,我更改了行:
$submittedToken = $this->app->request()->post($this->key) ?: '';
对此:
$submittedToken = $this->app->request->headers->get('X-XSRF-TOKEN') ?: '';
如果我是对的,这将为 $submittedToken 分配在标头中作为 X-XSRF-TOKEN 传递的值。它使用来自中间件“CSRF 令牌不匹配”的消息引发异常。这感觉像是进步。以下是相关的角度:
app.controller('itemsCtrl', ['$scope', '$http', function($scope, $http) {
// Initailize object when the page first loads
$scope.getAll = function() {
$http.post('/domain.com/admin/getNames').success(function(data) {
$scope.names = data;
});
}
编辑
下面是 php 代码现在所在的位置。我认为这是有效的。当我在提交表单之前删除 cookie 或更改 $token 的值时,我收到了预期的 CSRF 错误。我有点担心当我有多个用户时会发生什么。我还没有测试过。根据这次修订,保护看起来是否健全?
<?php
namespace Cache\Middleware;
use Exception;
use Slim\Middleware;
class CsrfMiddleware extends Middleware {
protected $key;
public function call() {
$this->key = $this->app->config->get('csrf.key');
$this->app->hook('slim.before', [$this, 'check']);
$this->next->call();
}
public function check() {
// if (!isset($_SESSION[$this->key])) {
if (!isset($_SESSION[$this->key])) {
// $_SESSION[$this->key] = $this->app->hash->hash($this->app->randomlib->generateString(128));
$this->app->setcookie($this->key, $this->app->hash->hash($this->app->randomlib->generateString(128)));
}
// $token = $_SESSION[$this->key];
if(isset($_COOKIE[$this->key])) {
$token = $_COOKIE[$this->key];
}
if (in_array($this->app->request()->getMethod(), ['POST', 'PUT', 'DELETE'])) {
// $submittedToken = $this->app->request()->post($this->key) ?: '';
$submittedToken = $this->app->request->headers->get('X-XSRF-TOKEN') ?: '';
if (!$this->app->hash->hashCheck($token, $submittedToken)) {
throw new Exception('CSRF token mismatch');
}
}
}
}