当我使用filsh / yii2-oauth2-server在yii2上构建oauth2 restful api时。它总是返回401。
控制器中的验证码
/**
* @return array
*/
public function behaviors()
{
return ArrayHelper::merge(parent::behaviors(), [
'authentication' => [
'class' => CompositeAuth::class,
'authMethods' => [
['class' => HttpBasicAuth::class],
['class' => HttpBearerAuth::class],
['class' => QueryParamAuth::class, 'tokenParam' => 'accessToken'],
],
],
'exceptionFilter' => [
'class' => ErrorToExceptionFilter::class
]
]);
}
配置文件中的代码
'oauth2' => [
'class' => \filsh\yii2\oauth2server\Module::class,
'components' => [
'request' => function () {
return \filsh\yii2\oauth2server\Request::createFromGlobals();
},
'response' => [
'class' => \filsh\yii2\oauth2server\Response::class,
],
],
'tokenParamName' => 'accessToken',
'tokenAccessLifetime' => 3600 * 24 * 7,
'storageMap' => [
'user_credentials' => 'common\models\User',
],
'grantTypes' => [
'user_credentials' => [
'class' => 'OAuth2\GrantType\UserCredentials',
],
'refresh_token' => [
'class' => 'OAuth2\GrantType\RefreshToken',
'always_issue_new_refresh_token' => true
]
],
],
用户模型中的代码
/**
* {@inheritdoc}
*/
public static function findIdentityByAccessToken($token, $type = null)
{
/** @var \filsh\yii2\oauth2server\Module $module */
$module = Yii::$app->getModule('oauth2');
$token = $module->getServer()->getResourceController()->getToken();
return !empty($token['user_id'])
? static::findIdentity($token['user_id'])
: null;
}
我的尝试
当我尝试查找问题时,我在用户模型中找到了问题。
$token = $module->getServer()->getResourceController()->getToken();
总是返回NULL,我不知道这是原因还是如何解决?