如何在yii2中添加哈希密码 [英] how to add hashed passwords in yii2

查看:153
本文介绍了如何在yii2中添加哈希密码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Yii 2 basic不是高级版。



我有一个crud管理认证系统。其中只存储数据库中的ID,用户名和密码。当用户登录时,如果用户名和密码正确,他们将登录。



然而,我现在想要使这些密码安全,所以我想盐和哈希他们。这是我发现很难做的部分或更多,以便放置在哪里。



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



我将首先介绍第一部分,因为它显然必须在此处生成散列密码。



AdminController:

  public function actionCreate()
{
$ model = new User();
$ b $ 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 

命名空间app \models;
使用yii\base\NotSupportedException;
使用yii\db\ActiveRecord;
使用yii\web\IdentityInterface;
使用yii\data\ActiveDataProvider;
/ **
*用户模型
*
* @property整数$ id
* @property字符串$用户名
* @property字符串$ password
* /
class用户扩展ActiveRecord implements IdentityInterface
{


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


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



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

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

返回$ dataProvider;



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



$ b / **
* @inheritdoc
* /
公共静态函数findIdentityByAccessToken($ token,$ type = null)
{
throw new NotSupportedException(''findIdentityByAccessToken'is not implemented。');
}

/ **
*通过用户名查找用户
*
* @param字符串$用户名
* @return static | null
* /
public static function findByUsername($ username)
{
return static :: findOne(['username'=> $ username]);

$ b / **
* @inheritdoc
* /
public function getId()
{
return $ this - >编号;

$ b / **
* @inheritdoc
* /
public function getAuthKey()
{
return static: :findOne( 'AUTHKEY');

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

/ **
*验证密码
*
* @param字符串$密码密码验证
* @return boolean if提供的密码对当前用户有效
* /
public function validatePassword($ password)
{
return $ this-> password === $ password;


问题:
所以,你可以在这个模型中看到我只有来自数据库的id,用户名和密码,所以我想我将需要创建一个字段在数据库称为hashed_pa​​ssword?

create.php:

 <?php $ form =的ActiveForm ::开始(); ?> 

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

<?= $ form->字段($ 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部分,需要生成并保存散列密码的实际位数据库,我该如何做到这一点?



好吧,继续 Part2:



SiteController:

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

$ model = new LoginForm(); ($ model-> load(Yii :: $ app-> request-> post())&& $ model-> login()){$ b $(

) b 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数组验证规则。
* /
公共函数规则()
{
return [
//用户名和密码都是必需的
[['username','password '],'required'],
// rememberMe必须是布尔值
['rememberMe','boolean'],
//验证密码validatePassword()
['password','validatePassword'],
];
}

/ **
*验证密码。
*此方法用作密码的内联验证。
*
* @param string $属性当前正在验证的属性
* @param array $ params规则中给出的额外名称/值对
* /
public function validatePassword($ attribute,$ params)
{
if(!$ this-> hasErrors()){
$ user = $ this-> getUser();

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

/ **
*使用提供的用户名和密码登录用户。
* @return boolean用户是否登录成功
* /
public function login()
{
if($ this-> validate()) {
return Yii :: $ app-> user-> login($ this-> getUser(),$ this-> rememberMe?3600 * 24 * 30:0);
} else {
return false;


$ b $ **
*通过[[username]]查找用户
*
* @return User | null
* /
public function getUser()
{
if($ this-> _user === false){
$ this-> _user = User: :findByUsername($这 - >用户名);
}

return $ this-> _user;


Login.php:

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

<?= $ form->字段($ model,'username'); ?>
<?= $ form->字段($ 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的User模型

  / ** 
*验证密码
*
* @param字符串$密码验证
*如果提供的密码对当前用户有效,则返回布尔值
* /
public function validatePassword($ password)
{
return Yii :: $ app-> getSecurity() - > ; validatePassword($ password,$ this-> password_hash);
}

而不是password_hash从db中使用您的字段。


using Yii 2 basic Not the advanced version.

I have a crud admin authentication system. Which stores just an id, username and password in the database. When the user goes to log in if the username and password are correct they are logged in.

However i now want to make these passwords secure so i want to salt and hash them. This is the part i am finding hard to do Or more so where to put things.

Part 1: I have an AdminController which goes along with my User Model Create.php page. Part 2: I have a siteController which goes along with the LoginForm model and the login.php page to log in.

I will go over part one first as it will obviously have to actually generate a hashed password here.

AdminController:

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;
}
}

Question??: So as you can see in this model i only have id, username and password coming from the database, so i take i will need to create one for field in db called "hashed_password"?

create.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(); ?>

Right so that was part 1, the actual bit where the hashed password needs to be generated and saved into the database, how can i achieve this?

Okay moving on the Part2:

SiteController:

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 (model):

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;
}
}

Login.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>

So thats it, how do i integrate a hashed_password for each user when they create and then validate this upon login?

I have been reading this on the documentation but just cant get this to work http://www.yiiframework.com/doc-2.0/guide-security-passwords.html

解决方案

When you creating user, you should generate and save password hash. To generate it

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

To check it on login, change your User model which implements 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);
    }

Instead of password_hash use your field from db.

这篇关于如何在yii2中添加哈希密码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆