php - Yii2 REST API doesn't return expected results -
i'm trying create simple rest api authentication. but, wrong.
i'm using advanced template yii framework 2. never had programed yii before, i'm learning.
my code:
~/api -->config --> 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' ] ], 'components' => [ 'user' => [ 'identityclass' => 'common\models\user', 'enableautologin' => false, ], '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/teste', 'extrapatterns' => [ 'get testando' => 'testando', ], ], [ 'class' => 'yii\rest\urlrule', 'controller' => 'v1/user', 'extrapatterns' => [ 'get login' => 'login', ], ], 'options v1/user/login' => 'v1/user/login', 'post v1/user/login' => 'v1/user/login', ], ] ], 'params' => $params, ]; --> modules --> v1 --> controllers --> testecontroller.php
<?php namespace api\modules\v1\controllers; //formato json use yii\filters\contentnegotiator; use yii\web\response; //banco de dados use yii\db\activerecord; //segurança use yii\filters\auth\compositeauth; use yii\filters\auth\queryparamauth; //rest api use yii\rest\activecontroller; /** * country controller api * * @author budi irawan <deerawan@gmail.com> */ class testecontroller extends activecontroller { public $modelclass = 'api\modules\v1\models\teste'; public function behaviors() { $behaviors = parent::behaviors(); $behaviors['authenticator'] = [ 'class' => queryparamauth::classname(), ]; $behaviors['bootstrap'] = [ 'class' => contentnegotiator::classname(), 'formats' => [ 'application/json' => response::format_json, ], ]; return $behaviors; } public function actiontestando(){ echo "testado"; } } --> modules --> v1 --> controllers --> usercontroller.php
<?php namespace api\modules\v1\controllers; use common\models\loginform; use yii\rest\activecontroller; class usercontroller extends activecontroller { public $modelclass = 'common\models\user'; public function actionlogin() { $model = new loginform(); if ($model->load(\yii::$app->getrequest()->getbodyparams(), '') && $model->login()) { echo \yii::$app->user->identity->getauthkey(); } else { return $model; } } public function actionindex() { if (\yii::$app->user->isguest) { throw new \httpheaderexception(); } return \yii::$app->user->getid(); } } --> modules --> v1 --> models --> teste.php
<?php namespace api\modules\v1\models; use yii\behaviors\timestampbehavior; use \yii\db\activerecord; class teste extends activerecord { /** * @inheritdoc */ public static function tablename() { return '{{%teste}}'; } /** * @inheritdoc */ public function behaviors() { return [ timestampbehavior::classname(), ]; } } --> modules --> v1 --> models --> user.php
<?php namespace api\modules\v1\models; use common\models\user commonuser; class user extends commonuser { } --> modules --> v1 --> module.php
<?php namespace api\modules\v1; class module extends \yii\base\module { public $controllernamespace = 'api\modules\v1\controllers'; public function init() { parent::init(); } } then when i'm testing rest api with:
curl -d- -u admin:123mudar! -h "content-type:application/json" 'http://www.domain.com/v1/testa/api/web/v1/testes' i've got:
http/1.1 401 unauthorized date: mon, 18 aug 2014 22:44:10 gmt server: apache transfer-encoding: chunked content-type: application/json; charset=utf-8 {"type":"yii\\web\\unauthorizedhttpexception","name":"unauthorized","message":"you requesting invalid access token.","code":0,"status":401} even when i'm using restclient plugin. missing?
database table structure:
create table if not exists `teste` ( `codigo` int(11) not null auto_increment, `nome` varchar(100) not null, primary key (`codigo`), key `nome` (`nome`) ) engine=myisam default charset=utf8 auto_increment=3 ; insert `teste` (`codigo`, `nome`) values (1, 'valor 1'), (2, 'valor 2'); create table if not exists `user` ( `id` int(11) not null auto_increment, `username` varchar(255) not null, `auth_key` varchar(32) not null, `password_hash` varchar(255) not null, `password_reset_token` varchar(255) default null, `email` varchar(255) not null, `role` smallint(6) not null default '10', `status` smallint(6) not null default '10', `created_at` int(11) not null, `updated_at` int(11) not null, primary key (`id`) ) engine=innodb default charset=utf8 auto_increment=2 ; insert `user` (`id`, `username`, `auth_key`, `password_hash`, `password_reset_token`, `email`, `role`, `status`, `created_at`, `updated_at`) values (1, 'admin', '79uf7p3xnv9t075lv1ka8g3myvaysaiw', '$2y$13$a8x5bngfswyn6rtftgz2h.ogu87gwqirrci/jzyzt.kwf6o6sltzc', null, 'admin@admin.com', 10, 10, 1408061655, 1408061655);
yii2 restful api use access-token authenticate instead of username:password , if user table doesn't have access_token column, create 1 , update user;
yii2 basic template's user model has access_token, below:
private static $users = [ '100' => [ 'id' => '100', 'username' => 'admin', 'password' => 'admin', 'authkey' => 'test100key', 'accesstoken' => '100-token', ], '101' => [ 'id' => '101', 'username' => 'demo', 'password' => 'demo', 'authkey' => 'test101key', 'accesstoken' => '101-token', ], ];
then, when request, use accesstoken username , left password empty, have try.
another way, can use use yii\filters\auth\queryparamauth; , use curl http://192.168.4.126/news/126?access-token=100-token test, both ok.
more detail, can refer article:
http://www.cnblogs.com/ganiks/p/yii2-restful-api-dev.html
at end, if want use username:password, can re-construct yii2-rest, refer :
http://www.cnblogs.com/ganiks/p/yii2-restful-api-mechanism.html
Comments
Post a Comment