yii2 oauth token validation on every page

2019-08-02 17:10发布

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?

  1. extending all controllers from some sort of base controller?
  2. bootstrapping a class in config?
  3. custom filter?
  4. behaviours?

Essentially I just need a function to run on every page except the 4 mentioned above.

1条回答
仙女界的扛把子
2楼-- · 2019-08-02 17:41

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 :

public function behaviors()
{
    $behaviors = parent::behaviors();
    $behaviors['authenticator'] = [
        'class' => CompositeAuth::className(),
        'authMethods' => [
            HttpBasicAuth::className(),
            HttpBearerAuth::className(),
            QueryParamAuth::className(),
        ],
    ];
    return $behaviors;
}

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 your SiteController :

public function behaviors()
{
    $behaviors = parent::behaviors();
    $behaviors['authenticator'] = [
        'class' => HttpBearerAuth::className(),
        'except' => ['login','logout','error','auth']
    ];
    return $behaviors;
}

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 or Yii::$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.

查看更多
登录 后发表回答