我正在通过rest api使用reactjs作为前端为现有Yii2应用程序构建身份验证(用户登录)。我面临的问题是,每当我向api发送一个post请求(localhost:8080 / v1 / users / login)时,它总是以仅以yii2实现的admin login(html)页面作为响应返回。
我尝试使用邮递员发送发帖请求,但仍然仅返回html登录页面。这是我的模块控制器和模型代码
web.php配置文件
<?php
$params = require(__DIR__ . '/params.php');
$config = [
'id' => '****',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
//I added the api module here
'modules' => [
'v1' => [
'class' => 'app\modules\v1\Module'
],
'debug' => 'yii\debug\Module',
],
'components' => [
'urlManager' => [
'class' => 'yii\web\UrlManager',
'showScriptName' => false,
'enablePrettyUrl' => true,
'rules' => [
[
'class' => 'yii\rest\UrlRule',
'controller' => 'v1/user',
'except' => ['delete']
],
'dashboard'=>'site/index',
'login'=>'site/login',
'branch/login'=>'branch/default/login',
'branch/dashboard'=>'branch/default/index',
'drivercorner/login'=>'drivercorner/default/login',
'drivercorner/dashboard'=>'drivercorner/default/index',
'company/login'=>'company/default/login',
'company/dashboard'=>'company/default/index',
'company/Driver'=>'company/memberdriver',
'company/AddDriver'=>'company/memberdriver/create',
'company/DriverDevices'=>'company/memberdevices',
'company/Vehicle'=>'company/membercar',
'company/driver/<action:\w+>/<id:\d+>'=>'company/driver/<action>',
'branch/driver/<action:\w+>/<id:\d+>'=>'branch/driver/<action>',
'<controller:\w+>/<id:\d+>' => '<controller>/view',
'<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
'<controller:\w+>/<action:\w+>' => '<controller>/<action>',
],
],
'response' => [
'formatters' => [
\yii\web\Response::FORMAT_JSON => [
'class' => 'yii\web\JsonResponseFormatter',
'prettyPrint' => YII_DEBUG, // use "pretty" output in debug mode
'encodeOptions' => JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE,
],
],
],
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => 'XwuLqf1zydUHdhd868tljcH7cqnxtvb9',
'parsers' => [
'application/json' => 'yii\web\JsonParser',
]
],
'cache' => [
'class' => 'yii\caching\FileCache',
],
'user' => [
'identityClass' => 'app\models\AdminUser',
'enableAutoLogin' => false,
],
'jwt' => [
'class' => 'sizeg\jwt\Jwt',
'key' => $params['TokenEncryptionKey'],
],
'errorHandler' => [
'errorAction' => 'site/error',
],
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'db' => require(__DIR__ . '/db.php'),
],
'params' => $params,
];
if (YII_ENV_DEV) {
// configuration adjustments for 'dev' environment
$config['bootstrap'][] = 'debug';
$config['modules']['debug'] = [
'class' => 'yii\debug\Module',
];
$config['bootstrap'][] = 'gii';
$config['modules']['gii'] = [
'class' => 'yii\gii\Module',
];
}
return $config;
UserController.php代码段
<?php
namespace app\modules\v1\controllers;
use Yii;
use yii\filters\AccessControl;
use app\modules\v1\models\User;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\UploadedFile;
use yii\web\Response;
use yii\rest\ActiveController;
/**
* UserController implements the CRUD actions for User model.
*/
class UserController extends ActiveController
{
public $modelClass = 'app\modules\v1\models\User';
public function behaviors()
{
$behaviors = parent::behaviors();
// add CORS filter
$behaviors['corsFilter'] = [
'class' => \yii\filters\Cors::className(),
];
$behaviors['authenticator'] = [
'class' => JwtHttpBearerAuth::className(),
];
$behaviors['authenticator']['except'] = ['login', 'signup'];
return $behaviors;
}
public function beforeAction($action)
{
Yii::$app->response->format = Response::FORMAT_JSON;
return true;
}
public function actionLogin()
{
// here you can put some credentials validation logic
//so if it success we return token
$email = \Yii::$app->getRequest()->post('email', '');
$password = \Yii::$app->getRequest()->post('password', '');
$user = null;
if($email && $password){
$user = User::findOne(['vEmail' => $email]);
}
if($user && $user->validatePassword(password) ){
$signer = new \Lcobucci\JWT\Signer\Hmac\sha256();
$expire = time() + \Yii::$app->params['JwtExpire'];
$jwt = \Yii::$app->jwt;
$token = $jwt->getBuilder()
->setId(\Yii::$app->params['TokenID'], true)// Configures the id (jti claim), replicating as a header item
->setIssuedAt(time())// Configures the time that the token was issue (iat claim)
->setExpiration($expire)// Configures the expiration time of the token (exp claim)
->set('uid', $user->id)// Configures a new claim, called "uid"
->sign($signer, $jwt->key)// creates a signature using [[Jwt::$key]]
->getToken(); // Retrieves the generated token
return $this->asJson([
'token' => (string)$token,
]);
}
\Yii::$app->response->statusCode = 401;
return ['msg' => 'username/password is wrong!'];
}
public function actionData()
{
return $this->asJson([
'success' => true,
]);
}
public function actionView($id)
{
return User::findOne($id);
}
}
User.php模型
namespace app\modules\v1\models;
use Yii;
use yii\helpers\Html;
use yii\grid\GridView;
use yii\helpers\ArrayHelper;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;
/**
* This is the model class for table "user".
*
* @property int $iUserId
* @property string $vFacebookId
* @property string $vInstagramId
* @property string $vTwitterId
* @property string $vFirstName
* @property string $vLastName
* @property string $vNickName
* @property string $vEmail
*/
class User extends ActiveRecord implements IdentityInterface
{
/**
* @inheritdoc
*/
public $social_id,$eLoginWith,$eUserType,$eDeviceType,
$vDeviceName,$vDeviceToken,$vAppVersion,$vDeviceId,$start_date,$end_date;
public static function tableName()
{
return 'user';
}
public static function findIdentityByAccessToken($token, $type = null)
{
$signer = new Sha256();
$decoded_token = (new Parser())->parse((string)$token); // Parses from a string
$data = new ValidationData(); // It will use the current time to validate (iat, nbf and exp)
$data->setId(Yii::$app->params['TokenID']);
if ($decoded_token->verify($signer, Yii::$app->params['TokenEncryptionKey'])) {
if ($decoded_token->validate($data)) {
$user = User::findOne(['$iUserId' => $decoded_token->getClaim('uid')]);
if ($user) {
return $user;
} else {
return null;
}
}
}
}
/**
* Validates password.
*
* @param string $password
* @return bool
*/
public function validatePassword($password)
{
return Yii::$app->security->validatePassword($password, $this->vPassword);
}
}
当我传递错误的路线或无效的参数时,我希望得到代码错误的响应。