Slim 3 中基于角色的身份验证和特权
Role based authentication and privilages in Slim 3
我实现了一个中间件来确定请求中发送的用户令牌的角色和有效性 header。
<?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;
}
}
以下函数returns角色名称(管理员、版主、客户等)
$this->container->authentication->isAuthenticatedForAdminSite($request)
如果 returns 没有任何用户被重定向到登录页面,否则我需要将 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 始终为 NULL,但当我在本地主机上测试应用程序时,它工作正常。
为服务(您从容器中获取的)提供任何状态是不好的做法。虽然我有点惊讶它无法正常工作,但更常见的做法是将您要获得的角色分配给请求:
// AuthenticationMiddleware
$response = $next($request->withAttribute('role', $role), $response);
然后,稍后在您的控制器中使用容器中可用的请求:
$request->getAttribute('role');
我实现了一个中间件来确定请求中发送的用户令牌的角色和有效性 header。
<?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;
}
}
以下函数returns角色名称(管理员、版主、客户等)
$this->container->authentication->isAuthenticatedForAdminSite($request)
如果 returns 没有任何用户被重定向到登录页面,否则我需要将 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 始终为 NULL,但当我在本地主机上测试应用程序时,它工作正常。
为服务(您从容器中获取的)提供任何状态是不好的做法。虽然我有点惊讶它无法正常工作,但更常见的做法是将您要获得的角色分配给请求:
// AuthenticationMiddleware
$response = $next($request->withAttribute('role', $role), $response);
然后,稍后在您的控制器中使用容器中可用的请求:
$request->getAttribute('role');