Yii2 REST API Bearer认证

3
我正在使用Yii2框架作为后端和react js作为客户端。我试图创建带有HTTPBearer身份验证的REST API,但始终遇到401未经授权的错误。我按照Yii2 Rest api身份验证指南进行操作,但没有成功。我还在user.php中实现了findIdentityByAccessToken和我的sql上的access_token。我的文件如下:-
文件夹结构:-
-api --config --main.php --main-local.php ... --modules --v1 --controllers --CheckinsController.php -backend -common -frontend ..
main.php
 <?php

$params = array_merge(
    require(__DIR__ . '/../../common/config/params.php'),
    require(__DIR__ . '/../../common/config/params-local.php'),
    require(__DIR__ . '/params.php'),
    require(__DIR__ . '/params-local.php')
);

return [
    'id' => 'app-api',
    'basePath' => dirname(__DIR__),
    'bootstrap' => ['log'],
    'modules' => [
        'v1' => [
            'basePath' => '@app/modules/v1',
            'class' => 'api\modules\v1\Module'   // here is our v1 modules
        ]
    ],
    'components' => [
        'user' => [
            'identityClass' => 'common\models\User',
            'enableAutoLogin' => false,
            'enableSession' => false,
            'loginUrl' =>'',
        ],
        'log' => [
            'traceLevel' => YII_DEBUG ? 3 : 0,
            'targets' => [
                [
                    'class' => 'yii\log\FileTarget',
                    'levels' => ['error', 'warning'],
                ],
            ],
        ],
        'request' => [
            'class' => '\yii\web\Request',
            'enableCookieValidation' => false,
    'parsers' => [
        'application/json' => 'yii\web\JsonParser',
    ]
],
        'urlManager' => [
            'enablePrettyUrl' => true,
            'enableStrictParsing' => true,
            'showScriptName' => false,
            'rules' => [
                [
                    'class' => 'yii\rest\UrlRule',
                    'controller' => 'v1/user', 
                    'tokens' => [
                        '{id}' => '<id:\\w+>'
                    ]
                ],
                  [
                    'class' => 'yii\rest\UrlRule',
                    'controller' => 'v1/event', 
                    'extraPatterns' => [
                    'GET test' => 'test'
                    ],     
                ],
                [
                    'class' => 'yii\rest\UrlRule',
                    'controller' => 'v1/checkins', 
                    'extraPatterns' => [
                     'GET checkinview/<id:\d+>' => 'checkinview/'
                    ],     
                ]
            ],
        ]
    ],
    'params' => $params,
];

CheckinsController.php

namespace api\modules\v1\controllers;

use yii\rest\ActiveController;
use yii\data\ActiveDataProvider;
use yii\filters\ContentNegotiator;
use api\modules\v1\models\CheckinApi;
use yii\filters\auth\HttpBearerAuth;
use yii\web\Response;

class CheckinsController extends ActiveController
{
    public $modelClass = 'common\models\Events';

public function behaviors()
{
    $behaviors = parent::behaviors();
    $behaviors['authenticator'] = [
        'class' => HttpBearerAuth::className()   
    ];
     $behaviors['contentNegotiator'] = [
            'class' => ContentNegotiator::className(),
            'formats' => [
                'application/json' => Response::FORMAT_JSON,
            ],
        ];

    return $behaviors;
}


public function actionCheckinview($id)
{
//     \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
    $query = new CheckinApi();
    $test = 
        [
            'count' => $query->Checkincount($id),
            'checkinid' => $id,
            'useridused' => Yii::$app->user->identity->id,

        ];
         return $test;//Testing purpose
}
}

User.php

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

/**
 * @inheritdoc
 */
public static function tableName()
{
    return '{{%user}}';
}

/**
 * @inheritdoc
 */
public function behaviors()
{
    return [
        TimestampBehavior::className(),
    ];
}

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

public function fields()
{
    $fields = parent::fields();

    // remove fields that contain sensitive information
    unset($fields['auth_key'], $fields['password_hash'], $fields['password_reset_token'],$fields['access_token']);

    return $fields;
}

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

/**
 * @inheritdoc
 */
public static function findIdentityByAccessToken($token, $type = null)
{
     return static::findOne(['access_token' => $token]);
}

/**
 * Finds user by username
 *
 * @param string $username
 * @return static|null
 */
public static function findByUsername($username)
{
    return static::findOne(['username' => $username, 'status' => self::STATUS_ACTIVE]);
}

/**
 * Finds user by password reset token
 *
 * @param string $token password reset token
 * @return static|null
 */
public static function findByPasswordResetToken($token)
{
    if (!static::isPasswordResetTokenValid($token)) {
        return null;
    }

    return static::findOne([
        'password_reset_token' => $token,
        'status' => self::STATUS_ACTIVE,
    ]);
}

/**
 * Finds out if password reset token is valid
 *
 * @param string $token password reset token
 * @return boolean
 */
public static function isPasswordResetTokenValid($token)
{
    if (empty($token)) {
        return false;
    }
    $expire = Yii::$app->params['user.passwordResetTokenExpire'];
    $parts = explode('_', $token);
    $timestamp = (int) end($parts);
    return $timestamp + $expire >= time();
}

/**
 * @inheritdoc
 */
public function getId()
{
    return $this->getPrimaryKey();
}

/**
 * @inheritdoc
 */
public function getAuthKey()
{
    return $this->auth_key;
}

/**
 * @inheritdoc
 */
public function validateAuthKey($authKey)
{
    return $this->getAuthKey() === $authKey;
}

/**
 * Validates password
 *
 * @param string $password password to validate
 * @return boolean if password provided is valid for current user
 */
public function validatePassword($password)
{
    return Yii::$app->security->validatePassword($password, $this->password_hash);
}

/**
 * Generates password hash from password and sets it to the model
 *
 * @param string $password
 */
public function setPassword($password)
{
    $this->password_hash = Yii::$app->security->generatePasswordHash($password);
}

/**
 * Generates "remember me" authentication key
 */
public function generateAuthKey()
{
    $this->auth_key = Yii::$app->security->generateRandomString();
}

 /**
 * Generates "api" access token
 */
public function generateAccessToken()
{
    $this->access_token = Yii::$app->security->generateRandomString($length = 16);
}

/**
 * Generates new password reset token
 */
public function generatePasswordResetToken()
{
    $this->password_reset_token = Yii::$app->security-       >generateRandomString() . '_' . time();
}

/**
 * Removes password reset token
 */
public function removePasswordResetToken()
{
    $this->password_reset_token = null;
}
}

Any help would be much appreciated!! trying to get around this problem for days, but no success. Dont know if it is a simple error done by me!!


你可以全部使用或者逐个使用。 - ovicko
4个回答

1

我有和你一样的情况。我在客户端使用ReactJS,在API方面使用Yii2。

对于你的情况,请检查以下规则:

[
    'class' => 'yii\rest\UrlRule',
    'controller' => 'v1/checkins', 
    'extraPatterns' => [
     'GET checkinview/<id:\d+>' => 'checkinview/'
    ],     
]

This code should be:

[
    'class' => 'yii\rest\UrlRule',
    'controller' => 'v1/checkins', 
    'tokens' => ['{id}' => '<id:\\w+>'], --> because you stil use ActiveController
    'pluralize' => false, --> for disable pluralize
    'extraPatterns' => [
     'GET checkinview/<id:\d+>' => 'checkinview' --> remove '/' sign
     'OPTIONS checkinview/<id:\d+>' => 'options', --> for corsFilter
    ],     
]

'OPTIONS checkinview/<id:\d+>' => 'options', --> for corsFilter 如果我没有这个会显示状态码为401吗?而在PostMan中相同的请求却可以正常工作。 - Harshit Chaudhary
1
如果您使用axios或fetch JS进行HTTP Promise,那么这是与CORS相关的。 OPTIONS请求用于检查是否允许执行GET、POST、DELETE、UPDATE操作。jQuery使用application/x-www-form-urlencoded格式,而axios或fetch使用application/json格式。请参见此链接 - muhammad aser

1
  • 给我"user.php"以便进行更多的检查...
  • "CheckinsController"应该像下面的LOCs一样(在你不控制它时不要添加更多信息)。

    namespace api\modules\v1\controllers;

    use yii\rest\ActiveController;
    use yii\data\ActiveDataProvider;
    use yii\filters\ContentNegotiator;
    use api\modules\v1\models\CheckinApi;
    use yii\filters\auth\HttpBearerAuth;
    use yii\web\Response;

    class CheckinsController extends ActiveController
    {
        public $modelClass = 'common\models\Events';

    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['authenticator'] = [
            'class' => HttpBearerAuth::className()   
        ]; 
        return $behaviors;
    } 
    }

感谢您的时间和回复,我会试一试。我还包括了user.php文件,请查看一下。我正在使用generateAccessToken方法来进行API操作。 - prasad mohan

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

-1
在我的情况下,当在firebug上检查时,会发出两个调用,一个是GET,另一个是OPTIONS。 GET将返回200 OK并且没有响应,而OPTIONS将返回401未经授权的访问。
在浏览谷歌时,发现这个简单的行就可以使它工作。
public function behaviors() {
    return
            \yii\helpers\ArrayHelper::merge(parent::behaviors(), [
                'corsFilter' => [
                    'class' => \yii\filters\Cors::className(),
                ],
                'authenticator' => [
                    'class' => \yii\filters\auth\HttpBearerAuth::className(),
                    'except' => ['options'],
                ],
    ]);
}

但是,我不明白为什么要使用OPTIONS,为什么GET没有返回响应?有人能详细解释一下吗?


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接