PHP 基于会话的身份验证问题,阻止 api 调用

PHP Session based authentication issue with blocking api calls

在我的 slim 应用程序上,我使用基于 cookie 的身份验证,在身份验证成功后,我设置 $_SESSION['id'],所以我可以知道用户已通过身份验证,现在我想在任何 API 调用之前检查用户是否已通过身份验证,但我不想检查用户是否正在调用 post 方法进行身份验证。下面是我的 index.php,如您所见,我正在检查会话,如果未设置 cookie,我只是 return http 错误。但是通过这种方式我被阻止进行身份验证调用,这意味着我无法登录到应用程序。禁用验证 post 调用检查的最佳方法是什么?

<?php
require 'vendor/autoload.php';

session_start();
if (empty($_SESSION['id'])) {
    http_response_code(423);
    exit('You are not authenticated, please authenticate!');
}
$app = new \Slim\App;

require_once 'rest/authentication/authentication.php';
require_once 'rest/users/users.php';
require_once 'rest/control-groups/controlGroups.php';
require_once 'rest/clients/clients.php';
require_once 'rest/attendants/attendants.php';
require_once 'rest/calendar/caringCalendar.php';

$app->run();

编辑:

这就是我的 index.php 的样子,感谢 Rob 的回答。

<?php
require 'vendor/autoload.php';

session_start();
$app = new \Slim\App;

$app->add(function($request,$response,$next) {
    // public route array
    $public = array('authenticate');

    // get the first route in the url

    $uri = $request->getUri();
    $path = explode('/', $uri->getPath());
    $requestRoute = $path[1];

    // if the first route in the url is not in the public array, check for logged in user
    if (!in_array($requestRoute,$public) && empty($_SESSION['id'])) {
        http_response_code(423);
        exit('You are not authenticated, plase authenticate!');
    }

    // public route or valid user
    return $next($request, $response);
});

require_once 'rest/authentication/authentication.php';
require_once 'rest/users/users.php';
require_once 'rest/control-groups/controlGroups.php';
require_once 'rest/clients/clients.php';
require_once 'rest/attendants/attendants.php';
require_once 'rest/calendar/caringCalendar.php';

$app->run();

您可能希望为您的路线使用 Middleware 并创建一个 public 不需要身份验证的路线列表。 注意:这只会使用url结构中的第一个路由。

    $app = new Slim\App;

// add middleware to routes
$app->add(function($request,$response,$next) {
    // public route array
    $public = array('authenticate');

    // get the first route in the url
    $uri = $request->getUri();
    $path = explode('/',$uri->getPath());
    $requestRoute = $path[1];

    // if the first route in the url is not in the public array, check for logged in user
    if (!in_array($requestRoute,$public) && empty($_SESSION['id'])) {
        return $response
                ->withStatus(401)
                ->write('You are not authenticated, please authenticate!');
    }

    // public route or valid user
    return $next($request,$response);
});

$app->get('/authenticate',function($request,$response) {
    return $response->write('Login');
});

$app->get('/admin',function($request,$response) {
    return $response->write('Admin page');
});

$app->run();