CSRF token doesn't work (yii2) with https - yii2

I test app on local is ok. I deploy to server with https domain. When i submit form then show 400 Error: Bad Request (#400): Unable to verify your data submission.
And have problem with Https, how can i fix it

Maybe you have got non-secure cookies blocked when sending over https. Try this in configuration:
return [
// ...
'components' => [
// ...
'request' => [
'class' => 'yii\web\Request',
'csrfCookie' => [
'httpOnly' => true,
'secure' => true,
],
],
],
];

Related

Swift_TransportException Failed to authenticate on SMTP server with username "example#gmail.com" using 2 possible authenticators

I am using yii2 mailer function and i am faced the issue the error is as below
Swift_TransportException
Failed to authenticate on SMTP server with username "example#gmail.com" using 2 possible authenticators. Authenticator LOGIN returned Swift_TransportException: Expected response code 235 but got code "535", with message "535 Incorrect authentication data
here is my configuration for mailer
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'viewPath' => '#common/mail',
'transport' => [
'class' => 'Swift_SmtpTransport',
'host' => 'smtp.gmail.com', // e.g. smtp.mandrillapp.com or smtp.gmail.com
'username' => 'example#gmail.com', //ses-smtp-user.20180221-103827 username: administrator
'password' => "example123#",
'port' => '587', // Port 25 is a very common port too 25, 465 or 587
'encryption' => 'tls', // It is often used, check your provider or mail server specs
'streamOptions' => [
'ssl' => [
'verify_peer' => false,
'verify_peer_name' => false,
]
],
],
// send all mails to a file by default. You have to set
// 'useFileTransport' to false and configure a transport
// for the mailer to send real emails.
'useFileTransport' => false,
],
if anyone knows what's the issue please let me know i am not getting where is the mistake thanks!

Session expire redirection on Ajax request in yii2

I want to redirect or send ajax response about the session expired in YII2.
Currently i am getting Forbidden(402) Login Required message as ajax response
you have an action that ajax request sent to it ,
you have to change accessControll to public for that action , to Anonymous access . (input this function in your controller )
use yii\filters\AccessControl;
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'actions' => ['view','you-action-name-for-ajax'],
'allow' => true,
// 'roles' => ['?'],
],
],
],
];
}
be sure to remove to Roles line .. I comment it .

Ignoring the default 404 route in ZF3 MVC

Currently, for my GET endpoints in RESTFUL Zend Framework 3, if I can't find the item the user requests through the paramaters I send 400 with JSON API errors like so:
$this->response->setStatusCode(Response::STATUS_CODE_400);
return JsonModel([
'errors' => [
[ 'title' => 'Not found' ]
]
]);
The correct status of course is 404. However as soon as I set $this->response->setStatusCode(Response::STATUS_CODE_404); the default 404 route is displayed. How do I disable it?
I tried commenting out the following in module.config.php
. . .
'view_manager' => [
// 'display_not_found_reason' => true,
'display_exceptions' => true,
'doctype' => 'HTML5',
// 'not_found_template' => 'error/404',
'exception_template' => 'error/index',
'strategies' => [
'ViewJsonStrategy',
],
. . .
],
That works, except I have two problems:
I'd like the 404 route for some endpoints
It adds information to the return JSON I don't want sent
{
"errors": [
{
"title": "Not Found",
}
],
"message": "Page not found.",
"display_exceptions": true,
"controller": "Company\Module\Controller\RestfulController",
"controller_class": null
}
What are my options?
Your issue is caused by Zend\Mvc\View\Http\RouteNotFoundStrategy, which is registered by your default view manager. You can see that at Zend\Mvc\View\Http\ViewManager:
$routeNotFoundStrategy = $services->get('HttpRouteNotFoundStrategy');
Even if you use 'display_exceptions' => false, message is still appended.
To overcome this, one solution is to inject the model content to the response and return the latter directly on your view:
$this->response->setStatusCode(Response::STATUS_CODE_404);
$model = new JsonModel([
'errors' => [
[ 'title' => 'Not found' ]
]
]);
return $this->getResponse()->setContent($model->serialize());

YII2 How to allow debug/default/toolbar in accesscontrol

I have the following configuration in the web.php file to force users to login first before using the app.
'as access' => [
'class' => \yii\filters\AccessControl::className(), //AccessControl::className(),
'rules' => [
[
'actions' => ['login', 'error'],
'allow' => true,
],
[
'actions' => ['logout', 'index'], // add all actions to take guest to login page
'allow' => true,
'roles' => ['#'],
],
],
],
However I get a Forbidden (#403) error in the http://localhost/yii2/debug/default/toolbar?tag=58759099581f2
How to allow in that in the rules?
First of all, this config is incorrect. This part:
[
'actions' => ['logout', 'index'], // add all actions to take guest to login page
'allow' => true,
'roles' => ['#'],
],
will additionally allow only logout and index actions to authenticated users. It needs to be changed to:
[
'allow' => true,
'roles' => ['#'],
],
to allow access to the entire site. Then you can customize access further in AccessControl or actions of specific controllers. So debug is not the only forbidden page in your case.
I think it was copy pasted from this answer to related question here on SO.
And by the way debug is already enabled in application config in basic app:
if (YII_ENV_DEV) {
// configuration adjustments for 'dev' environment
$config['bootstrap'][] = 'debug';
$config['modules']['debug'] = [
'class' => 'yii\debug\Module',
// uncomment the following to add your IP if you are not connecting from localhost.
//'allowedIPs' => ['127.0.0.1', '::1'],
];
// Below Gii is enabled too, code is omitted for brevity
}
So when user is authenticated, you will have access to debug module without any problems.
Note: With this configuration login and error actions of every controller are allowed to non-authenticated users. Be careful with that. There is a chance of actions with similar names exist in other controllers.
Update: Actually you can go further and make this solution more flexible with $matchCallback:
'as access' => [
'class' => \yii\filters\AccessControl::className(),
'rules' => [
[
'matchCallback' => function ($rule, $action) {
$allowedControllers = [
'debug/default',
];
$allowedActions = [
'site/login',
'site/error',
];
$isAllowedController = in_array($action->controller->uniqueId, $allowedControllers);
$isAllowedAction = in_array($action->uniqueId, $allowedActions);
return $isAllowedController || $isAllowedAction;
},
'allow' => true,
],
[
'allow' => true,
'roles' => ['#'],
],
],
],
Place fully allowed controllers in $allowedControllers list (prefix it with module name if it's inside a module) to allow them completetely (allow all actions).
Place allowed actions in $allowedActions list (prefix it with controller name and with module name if it belongs to a module).
That way you can have full access to debug module on local server on every page (including login and error) which can be useful.
Also this prevents from action names coincidence from different modules / controllers.
You have to enable the toolbar action web.php config file:
'rules' => [
[
'actions' => ['login', 'error', 'toolbar'],
'allow' => true,
],

Swiftmailer from Advanced Yii 2.0 does not work with gmail

I'm trying to configure swiftmailer in the advanced yii 2.0 template. I've gone through many posts and I understand that there are some issues with gmail. My configuration environment in development is the following:
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'viewPath' => '#common/mail',
'useFileTransport' => false,
'transport' => [
'class' => 'Swift_SmtpTransport',
'host' => gethostbyname('smtp.gmail.com'),
'username' => 'xxx#gmail.com',
'password' => 'xxssxxxx',
'port' => '465',
'encryption' => 'ssl'
]
I've also set the support mail that's used in the controller to the same gmail address in the main-local config shown above.
I've tried switching to a less secure configuration for apps in the gmail account and it did not work and I'm not particularly fond on changing this. I get the following error when I use ssl encryption
connection could not be established with host ... [ #0]
If I don't specify the encryption I get a time out error.
I have OpenSSL support enabled according to my phpinfo file but I cannot make it work. TLS does not work either because if I change the config (port:'587' & encryption='tls') I get the following error
stream_socket_enable_crypto(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed
Any ideas on how can I fix this? Is this an unfixed issue? Should I use another mailing extension?
The options can be set like this:
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'viewPath' => '#common/mail',
'useFileTransport' => false,
'transport' => [
'class' => 'Swift_SmtpTransport',
'host' => gethostbyname('smtp.gmail.com'),
'username' => 'xxx#gmail.com',
'password' => 'xxssxxxx',
'port' => '465',
'encryption' => 'ssl',
'streamOptions' => [
'ssl' => [
'allow_self_signed' => true,
'verify_peer' => false,
'verify_peer_name' => false,
],
]
]
Editor's note: disabling SSL verification has security implications. Without verification of the authenticity of SSL/HTTPS connections, a malicious attacker can impersonate a trusted endpoint (such as GitHub or some other remote Git host), and you'll be vulnerable to a Man-in-the-Middle Attack. Be sure you fully understand the security issues before using this as a solution.
Try using the gmail smtp IP
'transport' => [
'class' => 'Swift_SmtpTransport',
'host' => '64.233.171.108',
'username' => 'XXXXXXX#gmail.com',
'password' => 'XXXXXXX',
'port' => '587',
'encryption' => 'tls',
],
Some production servers cannot solve FQDN via DNS servers
For gmail: encryption must be setted to tls, port to 587 and host to smtp.gmail.com (check if your gethostbyname('smtp.gmail.com'), get the correct value) see the sample below:
'transport' => [
'class' => 'Swift_SmtpTransport',
'host' => 'smtp.gmail.com',
'username' => 'yourUsername#gmail.com',
'password' => 'yourPassword',
'port' => '587',
'encryption' => 'tls',
],
Please check :
Internet connection
email Configuration
This is my configuration. An Email succesfuly send.
'components'=>[
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'viewPath' => '#app/mail',
'useFileTransport' => false,
'transport' => [
'class'=>'Swift_SmtpTransport',
'host'=>'smtp.gmail.com', //sample
'username'=>'my#emaul.com', //sample email
'password'=>'~!##$%%^&&', // sample password
'port'=>'465', // gmail ssl use port 465,
'encryption'=>'ssl',
],
],
],
I had this issue my oversight being i was connecting with tls as my encryption , while the remote server only supported the older ssl encryption.
All i did was to change my encryption parameter value from "tls" to "ssl" and everything worked.
I hope this helps someone.
Adding streamOptions solved my problems!
'streamOptions' => [
'ssl' => [
'allow_self_signed' => true,
'verify_peer' => false,
'verify_peer_name' => false,
],
]