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

时间:2017-03-18 15:26:37

标签: php session authentication slim

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

<?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();

1 个答案:

答案 0 :(得分:1)

您可能希望将Middleware用于您的路线,并创建不需要身份验证的路线的公开列表。 注意:这只会使用网址结构中的第一条路径。

    $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();