Skip to content

Instantly share code, notes, and snippets.

@cebe
Created October 25, 2014 19:41
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save cebe/5ac9fea529750d63bcdd to your computer and use it in GitHub Desktop.
Save cebe/5ac9fea529750d63bcdd 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