问题描述
在我的系统中添加此代码后,我试图登录我的系统,但它给了我错误的请求方法 因为我不想禁用 CSrf 方法 这是在 layouts/main.PHP
<div class="wrap">
<?PHP
NavBar::begin([
'brandLabel' => Yii::$app->name,'brandUrl' => Yii::$app->homeUrl,]);
$menuItems = [
['label' => 'Home','url' => ['/site/index']],];
if (Yii::$app->user->isGuest) {
$menuItems[] = ['label' => 'Login','url' => ['/site/login']];
} else {
$menuItems[] = [
'label' => 'logout('.Yii::$app->user->user->identity->username.')','url' =>['/site/logout'],'linkOptions' =>[
'data-method'=> 'post'
]
];
}
然后是 SiteController.PHP
public function actionLogin()
{
if (!Yii::$app->user->isGuest) {
return $this->goHome();
}
$this->layout = 'blank';
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->login()) {
return $this->goBack();
} else {
$model->password = '';
return $this->render('login',[
'model' => $model,]);
}
}
解决方法
确保你的布局文件中有这个:
<?php $this->registerCsrfMetaTags(); ?>
您的表单中还需要一个 csrfInput。 如果您没有使用 ActiveForm 生成表单,则必须手动添加,例如:
<input type="hidden" name="<?= Yii::$app->request->csrfParam; ?>" value="<?= Yii::$app->request->csrfToken; ?>" />
csrfParam 默认为“_csrf”,但像这样使用它。将来您可能想要重命名它。