首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Yii2 REST承载身份验证

Yii2 REST承载身份验证
EN

Stack Overflow用户
提问于 2015-07-27 20:17:20
回答 4查看 14K关注 0票数 3

我使用Yii2框架作为后端, js用于客户端。我试图使用HTTPBearer身份验证来创建REST,但总是获得401未经授权的错误。我遵循了Yii2 Rest身份验证,但没有成功。我还在findIdentityByAccessToken上实现了user.php,在sql上实现了access_token。我的档案:-

文件夹结构:-

-api

.-配置

.=‘2’>中产

主要-local.php

更接近.

.模块

.=‘2’>.

.controllers=‘controllers 2’>.controllers=‘controllers 2’>.

-支票-Controller.php

-backend

-common

-frontend ..

main.php

代码语言:javascript
运行
复制
 <?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

代码语言:javascript
运行
复制
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;
}
}

任何帮助都将不胜感激!!试着解决这个问题好几天了,但没有成功。不知道这是不是我做的一个简单的错误!

EN

回答 4

Stack Overflow用户

发布于 2015-08-26 04:15:42

  • 给我"user.php“来检查更多..。
  • "CheckinsController“应该喜欢下面的LOCs (当您不控制它时不要添加更多信息)。
代码语言:javascript
运行
复制
    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;
    } 
    }
票数 1
EN

Stack Overflow用户

发布于 2016-10-08 05:50:15

我有和你一样的案子。我正在为客户端使用ReactJS,Yii2 for api。

在您的例子中,请检查以下规则:

代码语言:javascript
运行
复制
[
    'class' => 'yii\rest\UrlRule',
    'controller' => 'v1/checkins', 
    'extraPatterns' => [
     'GET checkinview/<id:\d+>' => 'checkinview/'
    ],     
]

这一守则应是:

代码语言:javascript
运行
复制
[
    '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
    ],     
]
票数 1
EN

Stack Overflow用户

发布于 2016-06-05 22:42:39

代码语言:javascript
运行
复制
 public function behaviors() {
    $behaviors = parent::behaviors();
    $behaviors['authenticator'] = [
        'class' => CompositeAuth::className(),
        'except' => ['token'],
        'authMethods' => [
            HttpBearerAuth::className(),
            QueryParamAuth::className(),
        ],
    ];
    return $behaviors;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31662459

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档