【发布时间】:2026-01-29 07:35:01
【问题描述】:
在我的瘦应用程序上,我使用基于 cookie 的身份验证,在成功的身份验证时我设置了 $_SESSION['id'],所以我可以知道用户已通过身份验证,现在我想在任何 API 调用之前检查用户是否已通过身份验证,但我不想检查用户是否正在调用 post 方法进行身份验证。下面是我的 index.php,你可以看到我正在检查会话,如果没有设置 cookie,我只会返回 http 错误。但是在这种方式下,我被阻止进行身份验证调用,这意味着我无法登录到应用程序。禁用对身份验证后调用检查的最佳方法是什么?
<?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();
【问题讨论】:
标签: php session authentication slim