进行身份验证的全局检查

进行身份验证的全局检查

本文介绍了Zend Framework 2 - 使用 ZFCUser 进行身份验证的全局检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我成功安装了 ZFCUser.现在我想知道是否有一种方法可以全局检查身份验证.

I installed ZFCUser successfully. Now I wonder if there is a way to globally check for authentication.

维基中所述 有几种方法可以检查身份验证.它们都有效,但我是否真的必须在每一个操作中加入 check-if-clause?我的所有网站都应该只有在登录时才能访问,否则,您应该重新路由到登录页面.

As outlined in the wiki there are several ways to check for auth. They all work but do I have to put the check-if-clause really in every single action? All my sites should be only accessable when beeing logged in and if not, you should be rerouted to the login page.

有人知道是否有一个可以放置这个逻辑的中心位置吗?

Does anybody know if there's a central place where I can put this logic?

推荐答案

老实说,我认为为未经身份验证的用户阻止每个页面并不是一个好主意.您将如何访问登录页面?

To be honest, I don't think it is a good idea to block every page for a non-authenticated user. How would you access the login page?

也就是说,您必须知道正在访问的页面,以便为匿名访问者提供可访问的页面白名单.首先,我建议包括登录页面.您可以使用他们的路线最简单地检查页面.所以根据白名单检查当前匹配的路由.如果被阻止,请采取行动.否则,什么都不做.

That said, you must know the page being accessed, to make a whitelist of pages accessible for anonymous visitors. To start, I'd suggest to include the login page. You can check pages the easiest by using their route. So check the current matched route against the whitelist. If blocked, act upon. Otherwise, do nothing.

一个示例位于模块的 Module.php 中,例如您的应用程序:

An example would be inside a Module.php from a module, for example your application:

namespace Application;

use ZendMvcMvcEvent;
use ZendMvcRouterRouteMatch;

class Module
{
    protected $whitelist = array('zfcuser/login');

    public function onBootstrap($e)
    {
        $app = $e->getApplication();
        $em  = $app->getEventManager();
        $sm  = $app->getServiceManager();

        $list = $this->whitelist;
        $auth = $sm->get('zfcuser_auth_service');

        $em->attach(MvcEvent::EVENT_ROUTE, function($e) use ($list, $auth) {
            $match = $e->getRouteMatch();

            // No route match, this is a 404
            if (!$match instanceof RouteMatch) {
                return;
            }

            // Route is whitelisted
            $name = $match->getMatchedRouteName();
            if (in_array($name, $list)) {
                return;
            }

            // User is authenticated
            if ($auth->hasIdentity()) {
                return;
            }

            // Redirect to the user login page, as an example
            $router   = $e->getRouter();
            $url      = $router->assemble(array(), array(
                'name' => 'zfcuser/login'
            ));

            $response = $e->getResponse();
            $response->getHeaders()->addHeaderLine('Location', $url);
            $response->setStatusCode(302);

            return $response;
        }, -100);
    }
}

这篇关于Zend Framework 2 - 使用 ZFCUser 进行身份验证的全局检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 09:18