将 OpenID 与 Zend Framework 结合使用

2024-01-16

我希望我的网站能够完全执行 Stackoverflow 使用 openId 所做的操作。

我正在梳理资料来源,之前我也曾在 facebook 上这样做过,但是 OpenID 方面没有取得太大进展。

我想做的只是检测是否有人登录了谷歌, 如果他们获得了一些身份信息,并允许他们 联合到我的网站。

任何人都可以建议任何教程或代码片段,我应该使用 Zends Libraries 吗?

-P


/**
 * SM's code library
 * 
 * @category    
 * @package     
 * @subpackage  
 * @copyright   Copyright (c) 2009 Pavel V Egorov
 * @author      Pavel V Egorov <[email protected] /cdn-cgi/l/email-protection>
 * @link        http://epavel.ru/
 * @since       29.04.2010
 */

/*
 * в configs/application.ini 
 * 
 * ;php-openid library
 * includePaths[] = APPLICATION_PATH "/../include/php-openid-2.1.3"
 * autoloadernamespaces[] = Auth_ 
 */


define ('Auth_Yadis_CURL_OVERRIDE', true);
define ('Auth_OpenID_RAND_SOURCE', null);

class Smapp_Auth_Adapter_OpenId implements Zend_Auth_Adapter_Interface
{
    /**
     * The identity value being authenticated
     *
     * @var string
     */
    protected $_id = null;

    /**
     * Reference to an implementation of a storage object
     *
     * @var Auth_OpenID_OpenIDStore
     */
    protected $_storage = null;

    /**
     * The URL to redirect response from server to
     *
     * @var string
     */
    protected $_returnTo = null;

    /**
     * The HTTP URL to identify consumer on server
     *
     * @var string
     */
    protected $_root = null;

    /**
     * Extension object or array of extensions objects
     *
     * @var string
     */
    protected $_extensions = null;

    /**
     * The response object to perform HTTP or HTML form redirection
     *
     * @var Zend_Controller_Response_Abstract
     */
    protected $_response = null;

    /**
     * Enables or disables interaction with user during authentication on
     * OpenID provider.
     *
     * @var bool
     */
    protected $_check_immediate = false;

    /**
     * Constructor
     *
     * @param string $id the identity value
     * @param Auth_OpenID_OpenIDStore $storage an optional implementation
     *        of a storage object
     * @param string $returnTo HTTP URL to redirect response from server to
     * @param string $root HTTP URL to identify consumer on server
     * @param mixed $extensions Auth_OpenID_Extension extension object or array of extensions objects
     * @param Zend_Controller_Response_Abstract $response an optional response
     *        object to perform HTTP or HTML form redirection
     * @return void
     */
    public function __construct($id = null,
                                Auth_OpenID_OpenIDStore $storage = null,
                                $returnTo = null,
                                $root = null,
                                $extensions = null,
                                Zend_Controller_Response_Abstract $response = null) {
        $this->_id         = $id;
        $this->_storage    = $storage;
        $this->_returnTo   = $returnTo;
        $this->_root       = $root;
        $this->_extensions = $extensions;
        $this->_response   = $response;

        //нужно потому что автозагрузчик зенда найти не может. там куча классов в одном файле
        require_once 'Auth/OpenID/SReg.php';
        require_once 'Auth/OpenID/PAPE.php';
    }

    /**
     * Authenticates the given OpenId identity.
     * Defined by Zend_Auth_Adapter_Interface.
     *
     * @throws Zend_Auth_Adapter_Exception If answering the authentication query is impossible
     * @return Zend_Auth_Result
     */
    public function authenticate() {

        $id = $this->_id;

        $consumer = new Auth_OpenID_Consumer($this->_storage);

        if (!empty($id)) {

            $authRequest = $consumer->begin($id);

            if (is_null($authRequest)) {
                return new Zend_Auth_Result(
                        Zend_Auth_Result::FAILURE,
                        $id,
                        array("Authentication failed", 'Unknown error'));
            }

            if (Auth_OpenID::isFailure($authRequest)) {
                return new Zend_Auth_Result(
                        Zend_Auth_Result::FAILURE,
                        $id,
                        array("Authentication failed", "Could not redirect to server: " . $authRequest->message));
            }

            $redirectUrl = $authRequest->redirectUrl($this->_root, $this->_returnTo);

            if (Auth_OpenID::isFailure($redirectUrl)) {
                return new Zend_Auth_Result(
                        Zend_Auth_Result::FAILURE,
                        $id,
                        array("Authentication failed", $redirectUrl->message));
            }

            Zend_OpenId::redirect($redirectUrl);

        } else {

            $response = $consumer->complete(Zend_OpenId::selfUrl());

            switch($response->status) {

                case Auth_OpenID_CANCEL:
                case Auth_OpenID_FAILURE:
                    return new Zend_Auth_Result(
                            Zend_Auth_Result::FAILURE,
                            null,
                            array("Authentication failed. " . @$response->message));
                break;

                case Auth_OpenID_SUCCESS:
                    return $this->_constructSuccessfulResult($response);
                break;
            }
        }
    }

    /**
     * @param Auth_OpenID_ConsumerResponse $response
     * @return Zend_Auth_Result
     */
    protected function _constructSuccessfulResult(Auth_OpenID_ConsumerResponse $response)
    {
        $identity = array();

        $identity['openid_identity'] = $response->getDisplayIdentifier();

        if ($response->endpoint->canonicalID) {
            $identity['openid_op_endpoint'] = $response->endpoint->canonicalID;    
        }
        if ($sreg = Auth_OpenID_SRegResponse::fromSuccessResponse($response)) {
            $identity['sreg'] = $sreg->contents();
        }
        if ($pape = Auth_OpenID_PAPE_Response::fromSuccessResponse($response)) {
            $identity['pape'] = (array)$pape;
        }

        return new Zend_Auth_Result(Zend_Auth_Result::SUCCESS, $identity, array("Authentication successful"));
    }

    /**
     * Sets the storage implementation which will be use by OpenId
     *
     * @param  Auth_OpenID_OpenIDStore $storage
     * @return Smapp_Auth_Adapter_OpenId Provides a fluent interface
     */
    public function setStorage(Auth_OpenID_OpenIDStore $storage)
    {
        $this->_storage = $storage;
        return $this;
    }

    /**
     * Sets the value to be used as the identity
     *
     * @param  string $id the identity value
     * @return Zend_Auth_Adapter_OpenId Provides a fluent interface
     */
    public function setIdentity($id)
    {
        $this->_id = $id;
        return $this;
    }

    /**
     * Sets the HTTP URL to redirect response from server to
     *
     * @param  string $returnTo
     * @return Zend_Auth_Adapter_OpenId Provides a fluent interface
     */
    public function setReturnTo($returnTo)
    {
        $this->_returnTo = $returnTo;
        return $this;
    }

    /**
     * Sets HTTP URL to identify consumer on server
     *
     * @param  string $root
     * @return Zend_Auth_Adapter_OpenId Provides a fluent interface
     */
    public function setRoot($root)
    {
        $this->_root = $root;
        return $this;
    }

    /**
     * Sets OpenID extension(s)
     *
     * @param  mixed $extensions
     * @return Zend_Auth_Adapter_OpenId Provides a fluent interface
     */
    public function setExtensions($extensions)
    {
        $this->_extensions = $extensions;
        return $this;
    }

    /**
     * Sets an optional response object to perform HTTP or HTML form redirection
     *
     * @param  string $root
     * @return Zend_Auth_Adapter_OpenId Provides a fluent interface
     */
    public function setResponse($response)
    {
        $this->_response = $response;
        return $this;
    }

    /**
     * Enables or disables interaction with user during authentication on
     * OpenID provider.
     *
     * @param  bool $check_immediate
     * @return Zend_Auth_Adapter_OpenId Provides a fluent interface
     */
    public function setCheckImmediate($check_immediate)
    {
        $this->_check_immediate = $check_immediate;
        return $this;
    }
}

现实世界的例子http://zonabarahla.ru/users/auth/login http://zonabarahla.ru/users/auth/login

source: http://zonabarahla.ru/users/auth/login?show-me-the-truth http://zonabarahla.ru/users/auth/login?show-me-the-truth

is uses http://openidenabled.com/files/php-openid/packages/php-openid-2.1.3.zip http://openidenabled.com/files/php-openid/packages/php-openid-2.1.3.zip

class Users_View_Helper_UsersLinker extends Zend_View_Helper_Abstract
{
    /**
     * @var Zend_View_Helper_Url
     */
    protected static $_urlHelper;

    /**
     * @return Users_View_Helper_UsersLinker
     */
    public function usersLinker()
    {
        return $this;
    }


    public function viewProfile($id) 
    {
        $options = array(
            'controller'    => 'view',
            'action'        => 'profile',
            'id'            => (int)$id
        );
        return $this->_url($options);
    }

    public function viewList()
    {        
        $options = array(
            'controller'    => 'view',
            'action'        => 'list',
        );
        return $this->_url($options);
    }

    public function crudUpdate($id)
    {
        $options = array(
            'controller'    => 'crud',
            'action'        => 'update',
            'id'            => (int)$id
        );
        return $this->_url($options);
    }


    public function login()
    {
        $options = array(
            'controller'    => 'auth',
            'action'        => 'login',
        );
        $url = $this->_url($options);
        return $url;
    }

    public function logout()
    {
        $options = array(
            'controller'    => 'auth',
            'action'        => 'logout'
        );
        return $this->_url($options);
    }

    /**
     * @return Zend_View_Helper_Url
     */
    public function getUrlHelper()
    {
        if (null === self::$_urlHelper) {
            self::$_urlHelper = new Zend_View_Helper_Url();
        }
        return self::$_urlHelper;
    }

    protected function _url($options, $routeName = null, $reset = true)
    {
        $urlHelper = $this->getUrlHelper();
        if (empty($options['module'])) {
            $options['module'] = $this->_getModuleName();
        }

        return $urlHelper->url($options, is_null($routeName) ? 'default' : $routeName, $reset);
    }

    protected function _getModuleName()
    {
        $moduleName = substr(get_class($this), 0, strpos(get_class($this), '_'));
        return strtolower($moduleName);
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将 OpenID 与 Zend Framework 结合使用 的相关文章

随机推荐

  • Android Studio 2 Beta 5 中的构建变体中测试工件选择器丢失/消失

    为了在 Android Studio 中运行 Instrumentation Tests 我通常通过 Build Variants 窗 口选择 Android Instrumentation Tests 作为要构建的测试工件 我最近升级到
  • 注入存储库上的 IDisposable

    我有以下 ADO Net 存储库 public class Repository IRepository IDisposable private readonly IUnitOfWork UnitOfWork private SqlConn
  • 使用 Ext.grid.Panel.reconfigure() 破坏网格 RowEditing 插件

    我正在创建一个 extjs 网格面板 其中有一组用户可配置的列 这Ext grid Panel http docs sencha com ext js 4 1 api Ext grid Panel组件提供了一个方便的reconfigure
  • 如何将卫星程序集(本地化资源)包含在使用 WiX 构建的 MSI 中?

    我正在从事的项目正在从使用 VS2008 部署 安装程序切换到 WiX 我目前对 WiX 还很陌生 我添加了将资源项目的输出复制到 Resources dll 中的代码 但在旧的 VS2008 安装程序文件系统中 还存在本地化资源输出 该输
  • 调用 mouseClicked() 后 JComponent 消失

    我正在用 Swing 编写一个 Java GUI 程序 界面如下所示 当用户单击右侧的其中一张图片时 我希望在左上角的橙色区域中显示它的小预览 我通过以下方式从计算机上的目录中提取所有图像文件SwingWorker线程 http docs
  • 无法打开登录请求的服务器

    我正在尝试使用 pyodbc 连接到我的 Azure SQL 数据库 我正在使用的azure帐户位于用户名下 电子邮件受保护 cdn cgi l email protection 我的大学帐户 当我尝试连接到数据库时 出现错误 Cannot
  • 如何在轮子中包含和安装测试文件并部署到 Databricks

    我正在开发一些在 Databricks 上运行的代码 鉴于 Databricks 无法在本地运行 我需要在 Databricks 集群上运行单元测试 问题是当我安装包含我的文件的轮子时 测试文件永远不会安装 如何安装测试文件 理想情况下我想
  • 如何在使用 VS Code 调试之前执行批处理文件

    我正在使用 Typescript nodeJS 和 VS Code 进行开发 使用 VS Code 进行调试 我的配置中有launch json type node request launch name Launch via NPM ru
  • 如何在 WPF ListView 中查看最后添加的列表视图项

    我正在使用视图模型绑定到列表视图 每次我在视图模型内部可观察集合中添加一个项目时 我都会使用 list Count 1 触发 LastIndex 属性 列表视图绑定到 VM 的 LastIndex 属性 并且列表视图正确选择添加到视图的最后
  • Typescript getter 和 setter 错误

    好吧 这是我第一天使用 typescript 做一些 Angular 2 我尝试制作一个简单的 getter 和 setter 服务 import Injectable from angular2 core Injectable expor
  • JPA:请帮助理解“join fetch”

    我有以下实体结构 业务 gt 营销活动 gt 促销 其中一个业务可以有许多营销活动 一个营销活动可以有许多促销活动 两个一对多关系都被声明为 LAZY 在我的代码中的一处 我需要急切地从 Business 中获取这两个集合 所以我这样做 Q
  • 在 data.table 中动态创建过滤表达式 (i)

    有一个data table library data table dd lt data table x 1 10 y 10 1 z 20 20 我可以使用过滤它 dd x in c 1 3 z in c 12 20 x y z 1 1 10
  • 如何屏蔽 EditText 以显示 dd/mm/yyyy 日期格式

    我怎样才能格式化EditText遵循 dd mm yyyy 格式化的方式与我们使用 a 格式化的方式相同TextWatcher to mask用户输入看起来像 0 05 我不是在谈论限制字符或验证日期 只是屏蔽到以前的格式 我写了这个Tex
  • 替换属于特定类的所有元素

    我试图开发一个嵌入式小部件 用户将包括一个anchor标签和页面中的 JavaScript 它将呈现内容 类似于嵌入式推文 a href http localhost 3000 user 13 target blank class my w
  • 添加新代码后 jQuery.keynav 不起作用

    我正在使用 jquery keynav 插件使用五个键在网页上执行导航 问题在于 我使用的是荧光笔 div 它引导用户浏览网页 可以获取 div 中的内容 文本等 并且可以执行多个操作 但荧光笔 div 不起作用 而是包含在网页 任何网页
  • JSTL 格式日期忽略区域设置

    我想用 JSTL 本地化日期 并且我正在尝试像下面那样执行此操作
  • 将数据结构从 java 传递到 perl(反之亦然)

    几天前 我询问了如何将数据结构从 java 传递到 perl 反之亦然 其中之一就是 JSON 我玩过它 主要使用 Gson for java 看起来相当不错 唯一的问题是我的数据结构内部有引用 同一数据结构内的其他对象 目前 每个此类引用
  • 词汇中的“这个”是什么? [复制]

    这个问题在这里已经有答案了 有人可以给我简单介绍一下词汇 this 吗 与函数表达式相比 箭头函数表达式 也称为胖箭头函数 具有更短的语法 并且在词法上绑定 this 值 不绑定自己的 this arguments super 或 new
  • 允许 this 引用转义

    我希望能帮助您理解 Java 并发实践 中的以下内容 调用可重写的实例方法 既不是 构造函数中的 private 或 Final 也可以允许 这个参考逃避 这里的 转义 是否仅仅意味着我们可能在实例完全构造之前调用实例方法 我没有看到 th
  • 将 OpenID 与 Zend Framework 结合使用

    我希望我的网站能够完全执行 Stackoverflow 使用 openId 所做的操作 我正在梳理资料来源 之前我也曾在 facebook 上这样做过 但是 OpenID 方面没有取得太大进展 我想做的只是检测是否有人登录了谷歌 如果他们获