To answer your questions, it is needed to understand one thing - Yii2
provides some helper classes / interfaces for developers to implement user authentication easily, but it is not always required to follow or use any of them. So my following answer is just explaining the default behavior of some classes.
And it is always a good starting point to look at the Yii2 Advanced template and the source code to understand the workflow of the framework, it is surprisingly easy to read, in my opinion.
- how does it work exactly
Yii2
framework provides a number of core components in its static context, you can always call them through Yii::$app->
. One of the core components is user
, it is actually an instance of yii\web\User
and all the default magic are inside this class.
Not only user
, you may also need to use other core components as well. I am not sure how deep you want to understand the way it works, if I don't give you a deep enough explanation, I strongly suggest you to read source code. You will have the source code on your hand once you did composer install
, or go to their github to have a code tracing - https://github.com/yiisoft/yii2/tree/master/framework
- All the steps required to complete authentication.
Firstly, you should have a User
class which implements IdentityInterface
and extends ActiveRecord
, please see the example in Advance template: https://github.com/yiisoft/yii2-app-advanced/blob/master/common/models/User.php .
And in your configuration, set the $identityClass
of user
component to the above custom User
class. This is the minimal setup for User
.
Next, you must have a controller with a method mapped to a request url such as "/login". In this method, you should use your way to extract the User
instance - $u
. This is the location where your authentication should be.
Then you can call Yii::$app->user->login($u)
to login; Yii::$app->user->logout()
to logout.
After you login, you can get the current user instance anywhere through Yii::$app->user->identity
.
- Required database fields or schema.
It is up to you, depending on your need. The template just gives you an idea on how to design the User
ActiveRecord class but not bounded by it - username
and passwordHash
are something very common but you can always have your own schema.
- How to authenticate multiple user types.
I don't quite understand the problem. Hope others could help.
- What may be a few other things I need to consider?
If you decide to use RESTful supported by the framework, remember to implement findIdentityByAccessToken()
in your User
class, see details in http://www.yiiframework.com/doc-2.0/guide-rest-authentication.html
I can think of one at this moment, may add other things later.