So I need to validate oauth token on every page except for site/login
, site/logout
, site/error
, site/auth
. Building off of the advanced template, this would obviously be in the backend.
What would be the proper way of doing this in Yii2?
- extending all controllers from some sort of base controller?
- bootstrapping a class in config?
- custom filter?
- behaviours?
Essentially I just need a function to run on every page except the 4 mentioned above.
Yii 2.0 already have 3 authentication methods implemented as filters :
Plus yii\filters\auth\CompositeAuth to use more than one at the same time. They are usually attached to each controller within a behavior :
And all of them have an
$except
and$only
properties to choose to which actions you are applying them. So you may have something like this in yourSiteController
:And you may have the the same behavior but without the
except
property in all the other controllers. Or you can make all the other controllers extends a common controller where that authenticator behavior is implemented.Those filters will use the built-in User class (as set in your config file) which implements the IdentityInterface to authenticate a user. That interface has already a findIdentityByAccessToken() method that you can use to validate a token instead of using findIdentity() to register a logged in user and make it accessible within
Yii::$app->user->identity
orYii::$app->user->id
.What I'm trying to explain here is kind of a summary of how Authentication is implemented within the built-in Yii RESTful API framework which may be better explained here :
http://www.yiiframework.com/doc-2.0/guide-rest-authentication.html
And which I consider a good exemple to follow. There is also this tutorial that describes authentication by access token and how it is implemented within the User class. It is about REST but the technique should be the same for a non REST app too as both are using the User class.