【问题标题】:Testing user identification before any request在任何请求之前测试用户身份
【发布时间】:2013-02-08 09:48:27
【问题描述】:

我想知道如何在整个模块中执行访问控制。让我解释一下:如果我有一个仅用于创建会话的模块(/authentication/)。还有一个包含主应用程序的模块(/Main/)。

如果用户正确创建了会话,我想做的是检查主模块上的任何请求。

在网上研究的过程中,我看到了一种方法。我不确定,所以告诉我我的解决方案是否好:我将在我的引导函数(在 module.php 上)中实现一个事件,该事件将检查会话是否正确创建。如果不是,我将重定向到模块身份验证。

public function onBootstrap($e){

    $eventManager = $e->getApplication()->getEventManager();

    $auth = new AuthenticationService();
    if (!$auth->hasIdentity()) {
        $response  = $e->getResponse();
        $response->getHeaders()->addHeaderLine('Location', 'authentification');
        $response->setStatusCode(302);
    }

    $moduleRouteListener = new ModuleRouteListener();
    $moduleRouteListener->attach($eventManager);
}

你觉得这个解决方案怎么样?

不幸的是,这个解决方案并不好。 我不知道为什么,但似乎即使在模块身份验证中也会执行此代码。 因此,在第一次调用时,当您尝试进入 url:/main 时,您将被重定向到模块 /authentication 并且代码将再次被重新执行,并且模块会将您重定向到 /authentication 并一次又一次地又...

所以我认为解决方案是检查请求的 url 是否与 /authentication 不同。

如何做到这一点?

希望我的问题清晰易懂。

谢谢你=D

【问题讨论】:

  • 您可能想查看现有的模块以及它们是如何做到的;) ZfcUser 和 BjyAuthorize 将是您目前的最高优先级。此外,这里也有一些关于这个主题的主题,搜索一下,你会找到它们。

标签: php zend-framework2 user-identification


【解决方案1】:
public function onBootstrap(MvcEvent $e) {

        $eventManager = $e->getApplication()->getEventManager();

        $eventManager->attach(MvcEvent::EVENT_DISPATCH, function($e) {

            $controller = $e->getTarget();
            $auth = new AuthenticationService();
            $is_login = $auth->hasIdentity();


                        //check if action is login

            $params = $e->getApplication()->getMvcEvent()->getRouteMatch()->getParams();

            if ($params['action'] == 'login') {


                if ($is_login) {
                    return $controller->redirect()->toRoute('adminindex');
                }

            } else {


                if (!$is_login) {
                    return $controller->redirect()->toRoute('adminauthlogin');
                }

            }
});

    }

更好的解决方案;)

【讨论】:

  • 或使用 ZfcUser 和 BjyAuthorize
  • 谢谢新浪,这正是我需要的=D
  • 欢迎您...任何其他 zf2 问题请标记或在您的问题中提及我...谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-05-03
  • 2021-11-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多