Last active
January 29, 2019 17:04
-
-
Save tunecino/cc067ff08acc43ce9071115312e19927 to your computer and use it in GitHub Desktop.
Yii2 Auto login user in RESTful API (Bearer/OAuth 2.0)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
public function beforeAction($action) | |
{ | |
if ($action->id !== 'options' && $action->id !== 'ping') { | |
/** | |
* Try to auto login user if auth headers are received within request. | |
*/ | |
$authHeader = Yii::$app->request->getHeaders()->get('authorization'); | |
if ($authHeader !== null) { | |
if (preg_match('/^Bearer\s+(.*?)$/', $authHeader, $matches)) { | |
$auth = Yii::$app->user->loginByAccessToken($matches[1], HttpBearerAuth::class); | |
$identity = $auth && $auth->id ? User::findIdentity($auth->id) : null; | |
if ($identity) { | |
Yii::$app->getUser()->login($identity); | |
} | |
} | |
} | |
} | |
return parent::beforeAction($action); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment