Php Slim 3中基于角色的身份验证和特权

Php Slim 3中基于角色的身份验证和特权,php,authentication,rendering,slim,middleware,Php,Authentication,Rendering,Slim,Middleware,我实现了一个中间件来确定在请求头中发送的用户令牌的角色和有效性 <?php namespace App\Middleware; class AuthenticationMiddleware extends Middleware { //Invoke magic method for all middlewares in Slim //Next is the next middle public function __invoke($request, $response, $next

我实现了一个中间件来确定在请求头中发送的用户令牌的角色和有效性

<?php
namespace App\Middleware;


class AuthenticationMiddleware extends Middleware {


//Invoke magic method for all middlewares in Slim
//Next is the next middle
public function __invoke($request, $response, $next) {

    $role = $this->container->authentication->isAuthenticatedForAdminSite($request);
     //$role  = 'Admin';
     if(!isset($role)) { 
        return $response->withRedirect('login'); 
     }
    $this->container->authentication->adminRole = $role;
    $response = $next($request, $response);
    return $response;
}
}
如果它不返回任何内容,则会将用户重定向到登录页面。如果不返回,则需要在身份验证中将to role的值保存到ivar adminRole。原因是,当我呈现页面时,我需要确定角色类型,以决定页面应显示何种导航栏

问题出现在路由功能的控制器中

public function getOrders($request, $response) {
    $role = $this->container->authentication->adminRole;

    return $this->container->view->render($response, 'orders.html', ['orders' => getOrdersForAdmin("%", $this->container->db), 'role' => $role]);
}

在共享主机上测试应用程序时,$role始终为空,但在本地主机上测试应用程序时,$role工作正常。

将服务(从容器中获取的服务)设置为任何状态都是错误的做法。虽然我有点惊讶它不能正常工作,但更常见的做法是将您获得的角色分配给请求:

// AuthenticationMiddleware
$response = $next($request->withAttribute('role', $role), $response);
然后,稍后在控制器中使用容器中提供的请求:

$request->getAttribute('role');

谢谢你的建议。我重构了我的代码,这无疑是一个更好的设计模式,特别是当你使用中间件时。
$request->getAttribute('role');