php - 在 Apigility Resource 中获取当前用户信息

标签 php zend-framework oauth-2.0 zend-framework2 laminas-api-tools

我刚开始使用 Apigility 和 oAuth2,我想知道在从数据库中获取信息时是否有可能获得当前经过身份验证的“已登录”用户。

我目前有以下代码:

/**
 * Fetch all or a subset of resources
 *
 * @param  array $params
 * @return mixed
 */
public function fetchAll($params = array())
{
    var_dump($params);
    // Using Zend\Db's SQL abstraction 
    $sql = new \Zend\Db\Sql\Sql($this->db); 
    //I would like to get the currently logged in user here... but how?
    $select = $sql->select('projects')->where(array('userid' => 1));; 

    // This provides paginated results for the given Select instance 
    $paged  = new \Zend\Paginator\Adapter\DbSelect($select, $this->db); 

    // which we then pass to our collection 
    return new ProjectsCollection($paged);  
}

我已经做了很多搜索,但我不知道如何访问用户信息或访问 token ,我是否需要为此解析请求 header ?

最佳答案

我也在找。我没有找到任何相关文件。但答案很简单:

资源类继承ZF\Rest\AbstractResourceListener,其中已经有一个方法getIdentity

/**
 * Fetch all or a subset of resources
 *
 * @param  array $params
 * @return mixed
 */
public function fetchAll($params = array())
{
    // if user isn't authenticated return nothing
    if(!$this->getIdentity() instanceof ZF\MvcAuth\Identity\AuthenticatedIdentity) {
        return [];
    }

    // this array returyour query here using $userIdns the authentication info
    // in this case we need the 'user_id' 
    $identityArray= $this->getIdentity()->getAuthenticationIdentity();

    // note, by default user_id is the email (username column in oauth_users table)
    $userId = $identityArray['user_id'];

    // fetch all using $userId
}

您还可以在 RPC 服务中使用 getIdentity

我使用的是最新版本的 apigility。

关于php - 在 Apigility Resource 中获取当前用户信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36722291/

相关文章:

php - 使用 Zend 进行 HTTP 身份验证

amazon-web-services - AWS Cognito-使用Google登录时如何强制选择帐户

php - 这种从数据库中选择随机记录的方法有什么缺陷吗?

javascript - Jquery文件上传。无法调整图像大小(原始缩略图)

php - 根据模式声明使用 Doctrine2 创建表和实体

php - Facebook Canvas 应用程序 "redirect_uri"在授权和身份验证后跳出 iframe

android - Oauth 2.0 : client id and client secret exposed, 是安全问题吗?

php - 在 WordPress 中回显 PHP 中的 HTML

Javascript 正则表达式相当于 PHP 正则表达式

php - 基于模块的项目 : when to use them or not use them