I have a backend project on my ssl server, like ssl.mybackend.com, with following:
class FormController extends Controller
{
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'actions' => ['index', 'delete', 'view', 'create'],
'allow' => true,
'roles' => ['#'], //only authorized users
],
[
'actions'=> ['create-order'],
'allow'=>true //change all users to "myfrontend.com"
]
],
],
];
}
I need to grant an access to create-order action only to my frontend website.
I am not sure if it's possible to do with AccessControl and appreciate if you could advise other solutions.
If you want to use ajax calls from frontend on another domain, you should use corsFilter instead. Example from documentation:
public function behaviors()
{
return [
'corsFilter' => [
'class' => \yii\filters\Cors::className(),
'cors' => [
// restrict access to
'Origin' => ['http://www.myserver.com', 'https://www.myserver.com'],
'Access-Control-Request-Method' => ['POST', 'PUT'],
// Allow only POST and PUT methods
'Access-Control-Request-Headers' => ['X-Wsse'],
// Allow only headers 'X-Wsse'
'Access-Control-Allow-Credentials' => true,
// Allow OPTIONS caching
'Access-Control-Max-Age' => 3600,
// Allow the X-Pagination-Current-Page header to be exposed to the browser.
'Access-Control-Expose-Headers' => ['X-Pagination-Current-Page'],
],
],
];
}
Cross Origin Resource Sharing in Yii2
Related
We developed our own api for mobile applications, which works on the basis of post requests, but after reinstalling the project on a new server, Yii :: $ app-> request-> post () always returns an empty value. At the same time, Yii :: $ app-> request-> getRawBody () contains a value, but I would not want to rewrite all api.
Tell me what could be the problem and which way to dig? Thanks in advance.
Sending through a mobile application or post through RestClient PHPStorm. Returns emptiness always.
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::class,
'only' => ['logout', 'signup'],
'rules' => [
[
'actions' => ['login'],
'allow' => true,
'roles' => ['?'],
],
[
'actions' => ['login'],
'allow' => true,
'roles' => ['#'],
],
],
],
'verbs' => [
'class' => VerbFilter::class,
'actions' => [
'login' => ['post', 'get'],
'token' => ['post', 'get'],
'logout' => ['post', 'get'],
],
],
];
}
public function beforeAction($action) {
$this->enableCsrfValidation = false;
return parent::beforeAction($action);
}
public function actionLogin()
{
return Yii::$app->request->post("username");
}
Could be your request is by get() method
$app->request->get();
After a new reinstallation of the project, the problem resolved by itself. Thanks to all.
Keep getting the cors issue.
Have already tried the following:
adding code you can see in the image in yii2
have installed the Cors Plugin in firefox
API URL : http://thisisbig.ae/advanced/backend/web/customersapi/update/?id=2
In the back-end ( Yii2 ), needed to override the verbs() function in the controller and add 'OPTIONS' for the 'update' value
protected function verbs()
{
return [
'index' => ['GET', 'HEAD'],
'view' => ['GET', 'HEAD'],
'create' => ['POST'],
'update' => ['PUT', 'PATCH','OPTIONS'],
'delete' => ['DELETE'],
];
}
Use a behavior to define this
public function behaviors()
{
return [
'verbs' => [
'class' => \yii\filters\VerbFilter::className(),
'actions' => [
'index' => ['GET'],
'view' => ['GET'],
'create' => ['GET', 'POST'],
'update' => ['GET', 'PUT', 'POST'],
'delete' => ['POST', 'DELETE'],
],
],
];
}
You can also use CORS filter by attaching it as a behavior to a controller or module, like the following,
public function behaviors()
{
return [
'corsFilter' => [
'class' => \yii\filters\Cors::className(),
],
];
}
you can also use CORS filter to restrict parameters, like this,
public function behaviors()
{
return [
'corsFilter' => [
'class' => \yii\filters\Cors::className(),
'cors' => [
// restrict access to
'Origin' => ['http://www.myserver.com', 'https://www.myserver.com'],
// Allow only POST and PUT methods
'Access-Control-Request-Method' => ['POST', 'PUT'],
// Allow only headers 'X-Wsse'
'Access-Control-Request-Headers' => ['X-Wsse'],
// Allow credentials (cookies, authorization headers, etc.) to be exposed to the browser
'Access-Control-Allow-Credentials' => true,
// Allow OPTIONS caching
'Access-Control-Max-Age' => 3600,
// Allow the X-Pagination-Current-Page header to be exposed to the browser.
'Access-Control-Expose-Headers' => ['X-Pagination-Current-Page'],
],
],
];
}
I have 2 controllers with some actions, I want to all requests expect those actions in the 2 controllers to be routed to invalid request page, how can I do that?
suppose:
controller1 => action1, action2, action3 allowed
controller2 => action4, action5, action6 allowed
all other requests should be go to bad request page.
Thank you.
Use Access Control, e.g. for controller 1:
public function behaviors()
{
return [
'access' => [
'class' => \yii\filters\AccessControl::className(),
'only' => ['action1', 'action2', 'action3'],
'rules' => [
[
'allow' => true,
],
// everything else is denied
],
],
];
}
As gmc specified you should use Access Control , however you might want to specify the "bad request" page.
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['action1', 'action2', 'action3'],
'rules' => [
[
'allow' => true,
],
],
'denyCallback' => function($rule, $action) {
return $this->redirect(['controller/action']);
}
],
];
}
How to navigate to index method without automatic login in frontend contoller ?
Extends behaviors method in SiteController:
use yii\filters\AccessControl;
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'actions' => ['index'],
'allow' => true,
],
[
'allow' => true,
'roles' => ['#'],
],
],
],
];
}
So index action will be available to everyone, instead other pages will require authentication
I am building an API in Yii2 and have added CORS and authentication. This works fine for all Create/Read/Update/Delete actions but not for custom actions. Has anyone experienced this before?
URL manager:
['class' => 'yii\rest\UrlRule', 'controller' => 'api/v1/user', 'pluralize' => false],
Controller behaviors:
public function behaviors()
{
return ArrayHelper::merge([
'corsFilter' => [
'class' => Cors::className(),
],
[
'class' => HttpBearerAuth::className(),
'except' => ['options',
'login',
],
],
], parent::behaviors()
);
}
As mentioned, actions for CRUD are fine but a custom action such as http://domain.com/user/test will respond with a 401 Unauthorised response.
Is it not possible to get CORS and auth to work together on custom actions?
Edit: I should add that the issue (401) occurs only when a browser makes the OPTIONS request. Normal requests (curl,Postman) are not affected. The issue seems to occur with the RESTful,Cors,Auth combination.
try this:
public function behaviors()
{
$behaviors = parent::behaviors();
unset($behaviors['authenticator']);
$behaviors['corsFilter'] = [
'class' => Cors::className(),
'cors' => [
'Origin' => ['*'],
'Access-Control-Request-Method' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'],
'Access-Control-Request-Headers' => ['*'],
'Access-Control-Allow-Credentials' => true,
],
];
$behaviors['authenticator'] = [
'class' => HttpBearerAuth::className(),
'except' => ['options','login'],
];
return $behaviors;
}
It will unset the default authenticator implemented by the parent controller to be sure that cors is treated first. Then we force cors to allow credentials before implementing your own authenticator.
The other thing that may raise that Unauthorized error is a not-found or wrong Options response as a browser request it first to get a list of allowed verbs. You may check that list in its headers response within your browser's network tab.
The general rule is when you ask your browser to perform a sensible verb like PUT, DELETE or POST to any url it may first send an OPTIONS request to that same url (check this) to check if that verb is allowed before sending the real request. So Yii should be configured to respond to all those OPTIONS verbs by performing the correct redirections.
The default CRUD actions implemented by ActiveController are using those default patterns:
'PUT,PATCH {id}' => 'update',
'DELETE {id}' => 'delete',
'GET,HEAD {id}' => 'view',
'POST' => 'create',
'GET,HEAD' => 'index',
'{id}' => 'options',
'' => 'options',
So whatever configurations you did implement in urlManager['rules'] be sure to not override the last 2 of them and if you are using custom patterns always remember to include its equivalent options verbs like in this example:
[
'class' => 'yii\rest\UrlRule',
'controller' => ['account' => 'auth/account'],
'patterns' => [
'POST,HEAD login' => 'login',
'POST,HEAD signup' => 'signup',
'POST req-reset-pass' => 'request-password-reset',
'POST reset-pass' => 'reset-password',
// OPTTIONS VERBS
'OPTIONS login' => 'options',
'OPTIONS signup' => 'options',
'OPTIONS req-reset-pass' => 'options',
'OPTIONS reset-pass' => 'options',
]
],
The same applies when adding custom patterns within extraPatterns.
The Options action is implemented by default in ActiveController. it's code can be seen here.
In case you are extending a different controller than ActiveController like maybe \yii\rest\Controller be sure to manually include it:
public function actions()
{
$actions = parent::actions();
$actions['options'] = [
'class' => 'yii\rest\OptionsAction',
// optional:
'collectionOptions' => ['GET', 'POST', 'HEAD', 'OPTIONS'],
'resourceOptions' => ['GET', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'],
];
return $actions;
}
Just move your corsFilter block above the authenticator block like this:
public function behaviors()
{
return [
'corsFilter' => [
'class' => \yii\filters\Cors::className(),
],
'authenticator' => [
'class' => HttpBearerAuth::className(),
],
'contentNegotiator' => [
'class' => ContentNegotiator::className(),
'formats' => [
'application/json' => Response::FORMAT_JSON,
],
],
];
}