api - Yii 2 RESTful API使用OAuth2进行身份验证(Yii 2高级模板)

标签 api rest oauth-2.0 yii2 yii2-advanced-app

REST API在没有身份验证方法的情况下可以正常工作。现在,我想通过OAuth2身份验证对REST API进行身份验证,以通过移动应用程序进行API请求。我尝试使用yii2指南,但对我而言不起作用。

基本上,移动用户需要使用用户名和密码登录,如果用户名和密码正确,则需要登录用户,并且需要使用 token 来验证进一步的API请求。

我需要像这样创建自定义OAuth 2客户端吗?
Creating your own auth clients

用户表中的access_token字段为空。我需要手动保存吗?
如何返回access_token作为响应?

一次同时使用这三种方法(HttpBasicAuth,HttpBearerAuth,QueryParamAuth)是否有任何原因,为什么?如何?

我的应用程序文件夹结构如下所示。

api
-config
-modules
--v1
---controllers
---models
-runtime
-tests
-web

backend
common
console
environments
frontend

api\modules\v1\Module.php
namespace api\modules\v1;
class Module extends \yii\base\Module
{
    public $controllerNamespace = 'api\modules\v1\controllers';

    public function init()
    {
        parent::init(); 
        \Yii::$app->user->enableSession = false;       
    }   
}

api\modules\v1\controllers\CountryController.php
namespace api\modules\v1\controllers;
use Yii;
use yii\rest\ActiveController;
use common\models\LoginForm;
use common\models\User;
use yii\filters\auth\CompositeAuth;
use yii\filters\auth\HttpBasicAuth;
use yii\filters\auth\HttpBearerAuth;
use yii\filters\auth\QueryParamAuth;

/**
 * Country Controller API
 *
 * @author Budi Irawan <deerawan@gmail.com>
 */
class CountryController extends ActiveController
{
    public $modelClass = 'api\modules\v1\models\Country';    

    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['authenticator'] = [
            //'class' => HttpBasicAuth::className(),
            'class' => CompositeAuth::className(),
            'authMethods' => [
                HttpBasicAuth::className(),
                HttpBearerAuth::className(),
                QueryParamAuth::className(),
            ],
        ];
        return $behaviors;
    }

}

common\models\User.php
namespace common\models;

use Yii;
use yii\base\NotSupportedException;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;

class User extends ActiveRecord implements IdentityInterface
{
    const STATUS_DELETED = 0;
    const STATUS_ACTIVE = 10;

    public static function tableName()
    {
        return '{{%user}}';
    }

    public function behaviors()
    {
        return [
            TimestampBehavior::className(),
        ];
    }

    public function rules()
    {
        return [
            ['status', 'default', 'value' => self::STATUS_ACTIVE],
            ['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_DELETED]],
        ];
    }

    public static function findIdentity($id)
    {
        return static::findOne(['id' => $id, 'status' => self::STATUS_ACTIVE]);
    }

    public static function findIdentityByAccessToken($token, $type = null)
    {

        return static::findOne(['access_token' => $token]);
    }


}

用户表
id
username
auth_key
password_hash
password_reset_token
email
status
created_at
access_token

在迁移用户表后添加了access_token

最佳答案

我正在使用JWT验证请求。基本上,JWT是一个 token ,还包含有关用户以及 token 本身的信息,例如 token 的有效性和过期时间。您可以阅读有关JWT here的更多信息。

我的应用程序的流程是这样的:

  • 首先,当用户登录时,为该用户创建一个JWT
    $key = base64_decode('some_random_string');
    
    $tokenId = base64_encode(mcrypt_create_iv(32));
    $issuedAt = time();
    $notBefore = $issuedAt + 5;
    $expire = $notBefore + 1800;
    
    $user = User::findByEmail($email);
    
    $data = [
        'iss' => 'your-site.com',
        'iat' => $issuedAt,
        'jti' => $tokenId,
        'nbf' => $notBefore,
        'exp' => $expire,
        'data' => [
            'id' => $user->id,
            'username' => $user->username,
            //put everything you want (that not sensitive) in here
        ]
    ];
    
    $jwt = JWT::encode($data, $key,'HS256');
    
    return $jwt;
    
  • 然后,客户端(例如移动应用)必须在每个请求中通过Authorization header 提供 token 。 header 将如下所示:
    Authorization:Bearer [the JWT token without bracket]
  • 在“用户”模型中,添加类似以下的方法来验证 token :
    public static function findIdentityByAccessToken($token, $type = null) {
        $key = base64_decode('the same key that used in login function');
    
        try{
            $decoded = JWT::decode($token, $key, array('HS256'));
            return static::findByEmail($decoded->data->email);
        }catch (\Exception $e){
            return null;
        }
    }
    

    如果 token 不再无效(已被篡改或已过期),则JWT库将引发Exception。
  • 然后,将其添加到每个 Controller 的行为函数中:
    $behaviors['authenticator'] = [
        'class' => HttpBearerAuth::className(),
        'except' => ['login'] //action that you don't want to authenticate such as login
    ];
    

  • 就是这样!我希望这项工作如您所愿。哦,您可以使用很多JWT库(可以在here中看到它),但是我个人使用this library by people from firebase

    关于api - Yii 2 RESTful API使用OAuth2进行身份验证(Yii 2高级模板),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29880655/

    相关文章:

    api - 谷歌 API 更改了来自谷歌金融的数据

    javascript - 检索 LinkedIn 访问 token

    php - Symfony2 一种API两种认证方式

    rest - Cowboy 多方法处理器

    java - 从字节数组创建损坏的 PDF

    java - 用于 Jersey 使用的(哈希) map 的序列化程序?

    amazon-web-services - 从 EndPoint LocalStorage AWS Cognito 获取访问 token

    oauth-2.0 - 如何从授权的 access_token 创建 GoogleCredential?

    javascript - 如何保护站点免受 API 中断的影响?

    java - 使用 REST API 在 Jira 中创建问题