Created
October 25, 2014 19:41
-
-
Save cebe/5ac9fea529750d63bcdd to your computer and use it in GitHub Desktop.
Yii2 API Auth with username and password
This file contains 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 | |
/** | |
* | |
* | |
* @author Carsten Brandt <[email protected]> | |
*/ | |
namespace api\components; | |
use common\models\ApiSystem; | |
use yii\filters\AccessControl; | |
use yii\filters\auth\HttpBasicAuth; | |
use yii\filters\ContentNegotiator; | |
use yii\filters\RateLimiter; | |
use yii\rest\Controller; | |
use yii\web\Response; | |
use Yii; | |
/** | |
* Base class for all API Controllers | |
*/ | |
abstract class BaseController extends Controller | |
{ | |
public function behaviors() | |
{ | |
return [ | |
'contentNegotiator' => [ | |
'class' => ContentNegotiator::className(), | |
'formats' => [ | |
'application/json' => Response::FORMAT_JSON, | |
], | |
], | |
'authenticator' => [ | |
'class' => HttpBasicAuth::className(), | |
'auth' => function ($username, $password) { | |
Yii::info("system attempts to login with '$username' and token '$password'", 'auth'); | |
return User::find()->active()->andWhere([ | |
'system_id' => $username, | |
'auth_token' => $password, | |
])->one(); | |
} | |
], | |
]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment