阻止api调用的基于PHP会话的身份验证问题
在我的slim应用程序上,我使用基于cookie的身份验证,在成功的身份验证时,我设置了$_SESSION['id'],这样我就可以知道用户已通过身份验证,现在我想在任何API调用之前检查用户是否已通过身份验证,但我不想检查用户是否正在调用post方法进行身份验证。下面是我的index.php,你们可以看到,我正在检查会话,若并没有设置cookie,我只返回http错误。但在这种情况下,我被阻止进行身份验证调用,这意味着我无法登录到应用程序。禁用身份验证后调用检查的最佳方法是什么阻止api调用的基于PHP会话的身份验证问题,php,session,authentication,slim,Php,Session,Authentication,Slim,在我的slim应用程序上,我使用基于cookie的身份验证,在成功的身份验证时,我设置了$_SESSION['id'],这样我就可以知道用户已通过身份验证,现在我想在任何API调用之前检查用户是否已通过身份验证,但我不想检查用户是否正在调用post方法进行身份验证。下面是我的index.php,你们可以看到,我正在检查会话,若并没有设置cookie,我只返回http错误。但在这种情况下,我被阻止进行身份验证调用,这意味着我无法登录到应用程序。禁用身份验证后调用检查的最佳方法是什么 <?ph
<?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();
您希望用于路由,并创建不需要身份验证的路由的公共列表。
注意:这将只使用url结构中的第一个路由
谢谢你,先生,我用我所做的修改更新了我的问题,你能再看一眼,看看是否可以。@SuperMario'sYoshi更新了我的答案。出于一致性的目的,我将使用Slim的响应方法with status()和write()。如果您决定使用您拥有的,正确的http状态将是401。
<?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();
$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();