Home » Php » php – Yii2: Why is the auth key in class User?

php – Yii2: Why is the auth key in class User?

Posted by: admin April 23, 2020 Leave a comment

Questions:

As the title clarifies why is the auth key introduced in Yii2? What’re it’s main usages and how it is useful in authentication?

How to&Answers:

The main use is to authenticate the user by cookie. When you choose to be remembered at Login, this is how you are remembered. The system has to identify and login you somehow. It can either save your username and password in a cookie (that would be unsafe) or it can remember you by other means. This is one of the means. After you login into your Yii application take a look at the _identity cookie that it creates, You will see that the auth_key is part of the cookie.

The cookie actually remembers the $id the $authKey and the $duration, an id\auth_key combination is safer to remember then a username/password one.

Answer:

As explained previously, you only need to implement getAuthKey() and validateAuthKey() if your application uses cookie-based login feature. In this case, you may use the following code to generate an auth key for each user and store it in the user table:

More details can be found in official documentation:
https://www.yiiframework.com/doc/guide/2.0/en/security-authentication