32

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?

gvlasov
  • 14,781
  • 17
  • 61
  • 99
Ejaz Karim
  • 3,495
  • 6
  • 33
  • 48

2 Answers2

45

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.

Mihai P.
  • 9,324
  • 3
  • 33
  • 47
  • 1
    Why not using default PHPSESSID and session for remembering? I mean you could set session timeout to week or month. – user1561346 Jan 30 '15 at 15:13
  • 1
    research changing the session timeout, you will see the problems with it. – Mihai P. Jan 30 '15 at 23:12
  • Can we use auth key for client auth in sessionless app – Robert Limanto Mar 24 '17 at 05:52
  • You probably can yes. but that means that you will need that info to authentificate the user. I built REST api (so sessionless) and I used a JWT to create a token that the server can trust. The server creates the JWT, passes it to the client, the client uses it on all requests, so the server trusts the info in it, because it encoded it. – Mihai P. Mar 26 '17 at 23:26
0

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

Junaid Atari
  • 499
  • 7
  • 14