Skip to content

Instantly share code, notes, and snippets.

@cebe
Created May 2, 2017 20:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cebe/ee7b62786d939ce73d237bde603cae3e to your computer and use it in GitHub Desktop.
Save cebe/ee7b62786d939ce73d237bde603cae3e to your computer and use it in GitHub Desktop.
allow basic auth for users not logged in
<?php
class SomeController extends yii\web\Controller
{
/**
* @var array actions to authenticate via basicAuth if not logged in.
*/
public $basicAuthActions = [];
/**
* Allow login via HTTP basic auth if iCal calendar url is used in Thunderbird or similar applications
*/
public function beforeAction($action)
{
// this has to come before calling the parent implementation
// so that we have a user instance to run access checks against
if (Yii::$app->user->isGuest && in_array($action->id, $this->basicAuthActions)) {
Yii::$app->user->enableSession = false;
$auth = new HttpBasicAuth();
$auth->auth = function($username, $password) {
$user = User::findIdentityByName($username);
if (!$user || !$user->validatePassword($password)) {
return null;
}
return $user;
};
$auth->beforeAction($action);
}
return parent::beforeAction($action);
}
// ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment