身份验证中间件Slim 3.0



如果未设置会话,我正在使用中间件重定向到登录页面。

$app->get('/dashboard', function (Request $request, Response $response, $args) {
include_once('employee-portal/dashboard.php');
return $response;})->add(new AuthMiddleware('counter', true, $app->getContainer()));

和我的中间件:

class AuthMiddleware implements MiddlewareInterface{
private $min_role = 'counter';
private $redirect = true;
private $container = null;
public function __construct($role_required, $login_redirect, $container)
{
    $this->min_role = $role_required;
    $this->redirect = $login_redirect;
    $this->container = $container;
}
public function __invoke($request, $response, $next)
{
    if ($this->userIsAuthorised()) {
        return $next($request, $response);
    } else {
        if ($this->redirect) {
            /**
             * @var SlimRouter router`
             */
            return $response->withRedirect(Details::getBaseUrl() . '/login' . '?ref=' . $request->getUri());
        }
        return $response->withStatus(401)->write("Sorry boss you are not authorised to see my secret");
    }
}
private function userIsAuthorised()
{
    if ($this->min_role == 'counter') {
        return true;
    } else if (SessionManager::isLoggedIn()) {
        if ($_SESSION['user_type']=='counter') {
            return true;
        }
    }
    return false;
}  }

但这是行不通的。我什至可以看到仪表板页面没有登录。即使登录后,我也无法访问$_SESSION['user_type']会话变量。

任何帮助都将被应用。预先感谢。

您将 'counter'传递到authmiddleware构造函数中,从而在if()的第一个CC_4语句中始终return true

if ($this->min_role == 'counter') 

将始终是正确的,因为您在构造函数中设置了$this->min = 'counter'。尝试重写new AuthMiddleware()和构造函数,以便您只需传递容器即可。在调用new AuthMiddleware()之前,您可以执行以下操作: $container['min_role'] = 'counter'如果您在应用程序中的其他地方需要它。

最新更新