Skip to content

Instantly share code, notes, and snippets.

@tunecino
Last active January 29, 2019 17:04
Show Gist options
  • Save tunecino/cc067ff08acc43ce9071115312e19927 to your computer and use it in GitHub Desktop.
Save tunecino/cc067ff08acc43ce9071115312e19927 to your computer and use it in GitHub Desktop.
Yii2 Auto login user in RESTful API (Bearer/OAuth 2.0)
<?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