【问题标题】:Zend 2 Authentication : Manage 2 IdentitiesZend 2 身份验证:管理 2 个身份
【发布时间】:2015-01-02 05:46:28
【问题描述】:

我正在使用 zend 2 身份验证。现在有一种情况,用户可以使用用户名和密码或电子邮件和密码登录。是否可以在 zend 2 中同时提供用户名和电子邮件作为身份。否则我该如何管理这种情况?

这是我当前的工作代码。这里使用电子邮件作为身份和密码作为凭据。

在 Module.php 中

public function getServiceConfig()
{
    return array(
        'factories' => array(

            'AuthService' => function($sm) {
                $dbTableAuthAdapter     = new DbTableAuthAdapter(
                    $sm->get('Zend\Db\Adapter\Adapter'),
                    'users',
                    'email',
                    'password'
                );
                $authService            = new AuthenticationService();
                $authService->setAdapter($dbTableAuthAdapter);
                return $authService;
            },

        )
    );
}

在控制器中,

  $this->getAuthService()->getAdapter()->setIdentity($oRequest->getPost('username'))->setCredential(md5($oRequest->getPost('password')));
            $select      = $this->getAuthService()->getAdapter()->getDbSelect();
            $select->where('is_active = 1');

            $oResult     = $this->getAuthService()->authenticate();

            // Authentication ends here 

            if ($oResult->isValid()) {
        // code after authentication
    }

有什么想法吗?谢谢。

【问题讨论】:

  • 这肯定需要一个自定义的身份验证适配器类,可能扩展Zend\Authentication\Adapter\DbTable\AbstractAdapter。您可以将“标识列”修改为有效列名的数组,并在authenticateCreateSelect 中构建选择查询时使用这些名称。

标签: php authentication zend-framework2


【解决方案1】:

如果您正在使用 Zend\Authentication\Adapter\DbTable 适配器,也许您可​​以尝试以下方法:

        $this->getAuthService()->getAdapter()
          ->setIdentity($oRequest->getPost('username'))
          ->setCredential(md5($oRequest->getPost('password')));
        $select  = $this->getAuthService()->getAdapter()->getDbSelect();
        $select->where('is_active = 1');

        $oResult = $this->getAuthService()->authenticate();

        if (!$oResult->isValid()) { //authentication by username failed, try with email
            $this->getAuthService()->getAdapter()->setIdentityColumn('email')
              ->setIdentity($oRequest->getPost('email'))
              ->setCredential(md5($oRequest->getPost('password')));

            $oResult = $this->getAuthService()->authenticate();
        }
        return $oResult->isValid();

【讨论】:

  • 其实我已经这样做了。但以同样的方式。无论如何感谢您的代码
【解决方案2】:

另一种方法是创建 2 个身份验证服务,一个用于电子邮件,另一个用于用户名。

当用户提交登录时,检查它是否是有效的电子邮件。在这种情况下,请使用电子邮件验证服务。否则,选择用户名认证服务。

您可以使用来自Zend website的zend电子邮件验证器检查它是否是有效的电子邮件

$validator = new Zend\Validator\EmailAddress();
if ($validator->isValid($login)) {
     // email appears to be valid
     // Use email authentication service
} else {
     // email is invalid; It may be the username.
     // use username authentication service
}

【讨论】:

    猜你喜欢
    • 2014-01-04
    • 1970-01-01
    • 2014-04-05
    • 1970-01-01
    • 2019-03-14
    • 2014-01-28
    • 2018-05-13
    • 2017-02-24
    • 1970-01-01
    相关资源
    最近更新 更多