Skip to content

Instantly share code, notes, and snippets.

@buttflattery
Forked from cebe/BaseController.php
Created January 19, 2019 12:01
Show Gist options
  • Save buttflattery/2e662abe92db8e7257cd6c895e394c2b to your computer and use it in GitHub Desktop.
Save buttflattery/2e662abe92db8e7257cd6c895e394c2b to your computer and use it in GitHub Desktop.
Yii2 API Auth with username and password
<?php
/**
*
*
* @author Carsten Brandt <mail@cebe.cc>
*/
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