gpt4 book ai didi

Yii2 Rest API 用户认证

转载 作者:行者123 更新时间:2023-12-04 23:39:43 27 4
gpt4 key购买 nike

我正在 yii2 中实现 Rest API。我想使用访问 token 对用户进行身份验证。我已经提到了各种SO答案如下

  • Rest api bearer authentication
  • Rest api bearer auth
  • Yii2 Rest api authentication

  • 但我不清楚我应该使用哪种身份验证方法以及如何获取用户身份。

    我创建了 findIdentityByAccessToken()我的用户身份类中的方法,如 Yii2 Rest guide 中所建议的.

    以下是 behaviour在我的 Controller 中实现
    public function behaviors() {
    $behaviors = parent::behaviors();
    $behaviors['authenticator'] = [
    'class' => HttpBasicAuth::className(),
    'except' => ['login','forgot-password']
    ];

    return $behaviors;
    }

    现在,我将如何在我的 Controller 操作中获取用户身份?据我所知,访问 token 将从请求 header 内的 Web 服务设置。

    注意:我使用的是 Yii2 高级应用程序
    请帮我。

    最佳答案

    简单的答案有不止一种可能性来实现这种行为。

    两者 HttpBearerAuthHttpBasicAuth可以使用 findIdentityByAccessToken()正确配置时的方法。您应该使用的行为取决于您希望用户对自己进行身份验证的方式。

    如果你阅读了 HttpBasisAuth 的文档HttpBasicAuth你会看到的

    The default implementation of HttpBasicAuth uses the loginByAccessToken() method of the user application component and only passes the user name. This implementation is used for authenticating API clients.


    loginByAccesToken将调用 findIdentityByAccesToken方法
    您可以通过在 auth 属性中定义闭包来操作此行为,请参阅 auth attribute .
    HttpBeareAuth几乎一样。它还实现了 loginByAccessToken
    那么是什么让两者彼此不同呢?简单的获取数据的位置。哪里 HttpBasicAuth期望客户端已经设置了基本头示例 header('Authorization: Basic '. base64_encode("user:password")); (PHP 已内置对此的支持,请参阅: http://php.net/manual/en/features.http-auth.php)
    HttpBearerAuth期望标题定义如下 header('Authorization: Bearer '. $token);
    因此,您应该使用的解决方案取决于您希望用户/客户端对自己进行身份验证的方式。您也可以使用 QueryParamAuth这使用户可以使用 GET 参数对自己进行身份验证,请参阅 queryparamauth

    如果您想使用自定义 header ,假设 X-API-Token 创建您自己的自定义类来实现 AuthMethod界面见 AuthMethod

    希望这可以帮助

    关于Yii2 Rest API 用户认证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41480771/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com