gpt4 book ai didi

php - 如何在 yii2 中添加哈希密码

转载 作者:行者123 更新时间:2023-12-03 00:56:05 25 4
gpt4 key购买 nike

使用 Yii 2 basic 而非高级版本。

我有一个 CRUD 管理员身份验证系统。它只在数据库中存储 ID、用户名和密码。当用户登录时,如果用户名和密码正确,他们就会登录。

但是我现在想要确保这些密码的安全,所以我想对它们进行加盐和哈希处理。这是我发现很难做的部分,或者更难做到把东西放在哪里。

第 1 部分:我有一个 AdminController 与我的用户模型 Create.php 页面一起使用。第 2 部分:我有一个 siteController,它与 LoginForm 模型和 login.php 页面一起登录。

我将首先讨论第一部分,因为它显然必须在此处实际生成哈希密码。

管理员 Controller :

public function actionCreate()
{
$model = new User();

if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}

User.php

    <?php

namespace app\models;
use yii\base\NotSupportedException;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;
use yii\data\ActiveDataProvider;
/**
* User model
*
* @property integer $id
* @property string $username
* @property string $password
*/
class User extends ActiveRecord implements IdentityInterface
{


/**
* @inheritdoc
*/
public static function tableName()
{
return 'Users';
}


public function rules(){
return [
[['username','password'], 'required']
];
}



public static function findAdmins(){
$query = self::find();

$dataProvider = new ActiveDataProvider([
'query' => $query,
]);

return $dataProvider;

}


/**
* @inheritdoc
*/
public static function findIdentity($id)
{
return static::findOne(['id' => $id]);
}



/**
* @inheritdoc
*/
public static function findIdentityByAccessToken($token, $type = null)
{
throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
}

/**
* Finds user by username
*
* @param string $username
* @return static|null
*/
public static function findByUsername($username)
{
return static::findOne(['username' => $username]);
}

/**
* @inheritdoc
*/
public function getId()
{
return $this->id;
}

/**
* @inheritdoc
*/
public function getAuthKey()
{
return static::findOne('AuthKey');
}

/**
* @inheritdoc
*/
public function validateAuthKey($authKey)
{
return static::findOne(['AuthKey' => $authKey]);
}

/**
* Validates password
*
* @param string $password password to validate
* @return boolean if password provided is valid for current user
*/
public function validatePassword($password)
{
return $this->password === $password;
}
}

问题??:因此,正如您在这个模型中看到的那样,我只有来自数据库的 ID、用户名和密码,所以我认为我需要为数据库中名为“hashed_pa​​ssword”的字段创建一个字段?

创建.php:

<?php $form = ActiveForm::begin(); ?>

<?= $form->field($model, 'username')->textInput(['maxlength' => 50]) ?>

<?= $form->field($model, 'password')->passwordInput(['maxlength' => 50]) ?>

<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>

<?php ActiveForm::end(); ?>

对,这就是第 1 部分,需要生成哈希密码并将其保存到数据库中的实际部分,我该如何实现这一点?

好的,继续第二部分:

站点 Controller :

public function actionLogin()
{
if (!\Yii::$app->user->isGuest) {
return $this->goHome();
}

$model = new LoginForm();

if ($model->load(Yii::$app->request->post()) && $model->login()) {
return $this->goBack();
} else {
return $this->render('login', [
'model' => $model,
]);
}
}

LoginForm.php(模型):

class LoginForm extends Model
{
public $username;
public $password;
public $rememberMe = true;

private $_user = false;


/**
* @return array the validation rules.
*/
public function rules()
{
return [
// username and password are both required
[['username', 'password'], 'required'],
// rememberMe must be a boolean value
['rememberMe', 'boolean'],
// password is validated by validatePassword()
['password', 'validatePassword'],
];
}

/**
* Validates the password.
* This method serves as the inline validation for password.
*
* @param string $attribute the attribute currently being validated
* @param array $params the additional name-value pairs given in the rule
*/
public function validatePassword($attribute, $params)
{
if (!$this->hasErrors()) {
$user = $this->getUser();

if (!$user || !$user->validatePassword($this->password)) {
$this->addError($attribute, 'Incorrect username or password.');
}
}
}

/**
* Logs in a user using the provided username and password.
* @return boolean whether the user is logged in successfully
*/
public function login()
{
if ($this->validate()) {
return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600*24*30 : 0);
} else {
return false;
}
}

/**
* Finds user by [[username]]
*
* @return User|null
*/
public function getUser()
{
if ($this->_user === false) {
$this->_user = User::findByUsername($this->username);
}

return $this->_user;
}
}

登录.php:

<?php $form = ActiveForm::begin(); ?>

<?= $form->field($model, 'username'); ?>
<?= $form->field($model, 'password')->passwordInput(); ?>


<div class="form-group">
<div class="col-lg-offset-1 col-lg-11">
<?= Html::submitButton('Login', ['class' => 'btn btn-primary', 'name' => 'login-button']) ?>
</div>
</div>

就是这样,我如何在每个用户创建时集成 hashed_pa​​ssword,然后在登录时验证它?

我一直在阅读文档,但就是无法让它工作 http://www.yiiframework.com/doc-2.0/guide-security-passwords.html

最佳答案

当您创建用户时,您应该生成并保存密码哈希。生成它

\Yii::$app->security->generatePasswordHash($password);

要在登录时检查它,请更改实现 UserIdentity 的用户模型

    /**
* Validates password
*
* @param string $password password to validate
* @return boolean if password provided is valid for current user
*/
public function validatePassword($password)
{
return Yii::$app->getSecurity()->validatePassword($password, $this->password_hash);
}

使用数据库中的字段代替password_hash。

关于php - 如何在 yii2 中添加哈希密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29490219/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com