我正在尝试登录系统时收到错误请求(#400)错误.我正在使用localhost.
主要布局:
content="width=device-width, initial-scale=1, maximum-scale=1"/>
= Html::csrfMetaTags(); ?>
= Html::encode($this->title); ?><?php $this->head(); ?>
查看(login.php):
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
$this->title = 'Login';
$this->params['breadcrumbs'][] = $this->title; ?>
Sign in to get in touch
method="post"
name="form"
class="form-validation">
class="form-control no-border" name="username">
class="form-control no-border" name="password">
Log in
站点控制器:
use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use app\models\LoginForm;
use yii\filters\VerbFilter;
class SiteController extends Controller {
public function behaviors() {
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'actions' => ['login', 'error'],
'allow' => true
],
[
'actions' => ['logout', 'index'],
'allow' => true,
'roles' => ['@']
]
]
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => ['logout' => ['post']]
]
];
}
public function actions() {
return ['error' => ['class' => 'yii\web\ErrorAction']];
}
public function actionIndex() {
return $this->render('index');
}
public function actionLogin() {
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->login()) {
return $this->goBack();
} else {
return $this->render('login', ['model' => $model]);
}
}
public function actionLogout() {
Yii::$app->user->logout();
return $this->goHome();
}
}
模型:
use Yii;
use yii\base\Model;
class LoginForm extends Model {
public $username;
public $password;
public $rememberMe = true;
private $_user = false;
public function rules() {
return [
[['username', 'password'], 'required'],
['rememberMe', 'boolean'],
['password', 'validatePassword']
];
}
public function validatePassword($attribute, $params) {
if (!$this->hasErrors()) {
$user = $this->getUser();
if (!$user || !$user->validatePassword($this->password)) {
$this->addError($attribute, 'Incorrect username or password.');
}
}
}
public function login() {
$duration = $this->rememberMe ? 3600 * 24 * 30 : 0;
if ($this->validate()) {
return Yii::$app->user->login($this->getUser(), $duration);
} else {
return false;
}
}
public function getUser() {
if ($this->_user === false) {
$this->_user = User::findByUsername($this->username);
}
return $this->_user;
}
}
为什么我收到此错误?我的代码有什么问题?
解决方法:
添加CSRF令牌.如果您不想使用ActiveForm,则显式添加此标记(如果使用ActiveForm,将自动添加标记):
name ="<?php echo Yii::$app->request->csrfParam; ?>"
value="<?php echo Yii::$app->request->csrfToken; ?>">
要为整个控制器禁用CSRF验证:
class DemoController extends Controller {
public $enableCsrfValidation = false;
}
要为某个操作禁用CSRF验证:
class DemoController extends Controller {
public function beforeAction($action) {
if (in_array($action->id, ['example'])) {
$this->enableCsrfValidation = false;
}
return parent::beforeAction($action);
}
}
标签:php,yii,yii2
来源: https://codeday.me/bug/20190528/1170033.html