I've turned the backend into an API. And the API controllers have HttpBasicAuth type authentication.
The problem is that even after authentication in the frontend, whenever a request is made to the API, the authentication window appears.
How can I do so that when the user authenticates in the frontend, is not requested again the username and password of access when a request is made to the API?
Example a controller in API:
class CategoryController extends ActiveController
{
public $modelClass = 'api\models\Category';
public function behaviors()
{
$behaviors = parent::behaviors();
$behaviors['authenticator'] = [
'class' => CompositeAuth::className(),
'authMethods' => [
[
'class' => HttpBasicAuth::className(),
'auth' => function($username, $password) {
$out = null;
$user = \common\models\User::findByUsername($username);
if ($user != null) {
if ($user->validatePassword($password)) $out = $user;
}
return $out;
}
],
],
];
return $behaviors;
}
}
It is called sharing sessions. It also depends on if your tier apps (frontend and api) are both in the same domain. If it is, configure your frontend and api settings (<app>/frontend/config/main.php and <app>/api/config/main.php) as follow:
'components' => [
...
'request' => [
'csrfParam' => '_csrf-shared',
],
...
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => true,
'identityCookie' => ['name' => '_identity-shared', 'httpOnly' => true],
],
...
'session' => [
'name' => 'advanced-shared',
],
...
It means you save cookies and session with the same name, so that when you login in frontend, and go to backend/api, the backend side fetches same cookies, therefore you'll be detected as authenticated user.
Here one important note, in order to enableAutoLogin work for both tiers, you should set same cookieValidationKey for both main-local.php settings. You can just set them manually, or edit init.php file to generate one cookieValidationKey for all tiers. (Just make sure you know what you're doing).
By the way, I think it's not a good idea to make simultaneous authentication between frontend and api. If it's frontend and backend then it's still bearable, but api interaction is different compared to frontend.
I suggest to use headers like Authorization: Bearer <token>.. You can get more information about it here Yii2 Rest Authentication
Update
I assume this is what you need.. Create a class, i.e. ApiAuth in common/components folder and paste the following code:
<?php
namespace common\components;
use yii\filters\auth\HttpBasicAuth;
class ApiAuth extends HttpBasicAuth
{
/**
* #inheritdoc
*/
public function authenticate($user, $request, $response)
{
if ($user->identity) {
return $user->identity;
}
return parent::authenticate($user, $request, $response);
}
}
This class extends from yii\filters\auth\HttpBasicAuth. Before calling a browser prompt it checks whether user->dentity is populated. If so, no promt is required.
In your Controller behavior replace HttpBasicAuth with ApiAuth class:
use common\components\ApiAuth;
...
'authMethods' => [
[
'class' => ApiAuth::className(),
'auth' => function($username, $password) {
...
As the user is already authenticated, then I just set the "AccessControl" for connected users. If they are not connected they will receive code 403 instead of 401.
This solves the problem:
class CategoryController extends ActiveController
{
public $modelClass = 'api\models\Category';
public function behaviors()
{
$behaviors = parent::behaviors();
$behaviors['access'] = [
'class' => \yii\filters\AccessControl::className(),
'rules' => [
[
'allow' => true,
'roles' => ['#'],
],
],
];
return $behaviors;
}
}
Related
I have a very basic Codeigniter 4 REST API with only one user and one function (POST). I need to add basic authentication where the username and password are in the HTTP authentication header. How do I add that to the code below? i don't need anything very sophisticated, just enough to authenticate the one user.
namespace App\Controllers;
use CodeIgniter\RESTful\ResourceController;
use CodeIgniter\API\ResponseTrait;
use App\Models\ApiModel;
use Config\Services;
class Api extends ResourceController {
use ResponseTrait;
protected $request;
public function create() {
$model = new ApiModel();
$data = [
'uid' => $this->request->getPost('uid'),
'request' => $this->request->getPost('request'),
'data' => $this->request->getPost('data')
];
$model->insert($data);
$response = [
'status' => 201,
'error' => null,
'messages' => [
'success' => 'Data Saved'
]
];
return $this->respondCreated($data, 201);
}
}
I have a controller with many actions. Now I want to use token-based authentication so I changed the behavior like this:
public function behaviors()
{
return [
'authenticator' => [
'class' => CompositeAuth::className(),
'only' => [
'logout',
'revoke'
],
'authMethods' => [
HttpBasicAuth::className(),
HttpBearerAuth::className(),
QueryParamAuth::className(),
],
]
];
}
This code works well but there is one problem.
I want to handle the unauthorized users by myself (not Yii) but when there is an unauthorized user send a request to my action, my action doesn't work and it will return Yii's default error.
How can I tell Yii to just authenticate the user (because I want to use Yii::$app->user->isGuest) and don't send default error?
UPDATE: I just want to disable the authenticator errors, I need other errors.
Yii2
PHP 7.2
You may use $optional property to configure actions where authentication should be optional (should not throw error). If it should be optional for all actions, you may use * instead of action name:
public function behaviors()
{
return [
'authenticator' => [
'class' => CompositeAuth::className(),
'optional' => ['*'],
// ...
]
];
}
I have an intranet app running on IIS, using CakePHP 3. From IIS I am able to access the server var $_SERVER['AUTH_USER'] and I want to use this variable to authenticate users.
I have created a users table in my database with a username field that I want to match to AUTH_USER. I have created a custom Auth component like so:
namespace App\Auth;
use Cake\Auth\BaseAuthenticate;
use Cake\Network\Request;
use Cake\Network\Response;
use Cake\ORM\TableRegistry;
class AuthuserAuthenticate extends BaseAuthenticate
{
public function authenticate(Request $request, Response $response) {
$username = str_replace('DOMAIN\\', '', $_SERVER['AUTH_USER']);
$users = TableRegistry::get('Users');
$user = $users->find()->where(['username' => $username])->first();
if ($user) {
return $user;
} else {
$user = $this->Users->newEntity();
$user->username = $username;
if ($this->Users->save($user)) {
return $user;
} else {
return false;
}
}
}
And in the AppController initialize() I have tried to load Auth with the custom component.
$this->loadComponent('Auth', [
'authenticate' => [
'Basic' => [
'fields' => ['username' => 'username'],
'userModel' => 'Users'
],
],
'loginAction' => [
'controller' => 'Pages',
'action' => 'display'
],
'storage' => 'Memory',
'unauthorizedRedirect' => false
]);
$this->Auth->config('authenticate', 'Authuser');
At this point I just get redirected no matter what page I try to go on, I'm not really sure if it's failing to authenticate or something else is the problem.
I have tried adding this to AppController as a test:
public function isAuthorized($user)
{
return true;
}
But I am unable to access any pages with this code in place. Can anyone let me know what I'm doing wrong?
Thanks,
Kez
Your auth component is not implementing the authorize method.
public function authorize($user, Request $request) {
// return true if authorized
// return false if not authorized
}
Secondly, isAuthorized is called when using the ControllerAuthorize component. If you want to use controller authentication, you should use ControllerAuthorize insted.
$this->loadComponent('Auth', [
'authenticate' => 'Controller'
]);
Also: You are configuring the BasicAuthenticate component, then immediately overwriting the config.
I have a rest full API in Yii2. I have the user model, controller and created a new rest action called login.
How can I set the action login to be executed by the guest users?
class UserController extends \yii\rest\ActiveController{
public function actions() {
$actions = parent::actions();
$actions['login'] = [
'class' => 'app\modules\user\actions\user\LoginUserAction',
'modelClass' => $this->modelClass,
'checkAccess' => [$this, 'checkAccess'],
];
return $actions;
}
public function checkAccess($action, $model = null, $params = array()) {
return true;
}
}
You can set the access control rules on the behaviors function of your controller, instead of on the checkAccess property on the action:
public function behaviors()
{
$behaviors = parent::behaviors();
$behaviors['access'] = [
'class' => AccessControl::className(),
'except' => ['login'],
'rules' => [
[
'allow' => true,
'actions' => ['foo', 'foo2'],
'roles' => ['admin'],
]
],
];
return $behaviors;
}
In this example, the access control is applied to all actions except 'login'. I left the rules part so you can have an example of how you make customized rules.
I have a module calls API, and i want to load config file for it. The guide says that i have to use function \Yii::configure. I use it, but it doesn't apply any new configs. And i tried to use array instead config file, the result is same
class API extends \yii\base\Module
{
public $controllerNamespace = 'api\client\controllers';
public function init()
{
parent::init();
// \Yii::configure($this, require(__DIR__ . '/config/main.php'));
\yii::configure($this, [
'components' => [
'user' => [
'class' => 'yii\web\UserTest',
'identityClass' => 'api\client\models\User',
],
]
]);
echo \yii::$app->user->className();
die();
}
}
How I can override config in my module ?
UPDATE
You have to use setComponents method of Yii::$app
Yii::$app->setComponents(
[
'errorHandler'=>[
'errorAction'=>'forum/forum/error',
'class'=>'yii\web\ErrorHandler',
],
'user' => [
'class' => 'yii\web\User',
'identityClass' => 'app\modules\profile\models\User',
],
]
);
OLD ANSWER
Didn't it give you errors? Your casing are wrong and so instead of "yii" in small letters use "Yii" capitalized
class API extends \yii\base\Module
{
public $controllerNamespace = 'api\client\controllers';
public function init()
{
parent::init();
\Yii::configure($this, [
'components' => [
'user' => [
'class' => 'yii\web\UserTest',
'identityClass' => 'api\client\models\User',
],
]
]);
echo \Yii::$app->user->className();
die();
}
}
I see no reason to override the application components here. I'd use #StefanoMtangoo trick but to set the component to the Module itself instead of Yii::$app:
public function init()
{
parent::init();
$this->setComponents([
'db' => [
'class' => 'yii2tech\filedb\Connection',
'path' => '#app/builder/data',
]
]);
}
Then the tricky part is to differentiate between any app's components and your module's own components. For example if my Module had a model extending yii\db\ActiveRecord I'd override its getDB() as follow (original code here):
public static function getDb()
{
return Yii::$app->getModule('api')->get('db');
// instead of: return Yii::$app->getDb();
}
So whatever the app that is using my module has or hasn't a db component it won't matter.