CSRF token mismatch in iframe (The Good fix ?) - laravel-5

Form submission in <iframe> using laravel throwing 419 CSRF token mismatch error
I came across couple of solutions but want's a secure one
Please assist which approach is better keeping good security
Excluding URIs From CSRF Protection https://laravel.com/docs/8.x/csrf#csrf-excluding-uris
Extend Cookie Support for SameSite=None, Secure https://laracasts.com/discuss/channels/laravel/embedding-laravel-form-in-iframe-shows-419-csrf-token-mismatch-error
Thanks

This solution is working for me
Yes, you can play with the config/session.php same_site value.
'same_site' => 'lax'
to
'same_site' => 'none',
add in your .env file
SESSION_SECURE_COOKIE=true

Related

Laravel 9 SPA athentication with nuxt, is saving tokens and sessions in cookies safe?

So I am making a web app with nuxt 3 and laravel, and I cant seem to get the SPA authentication to work. So I am for now generating a usertoken and saving it in the cookies, so my user keeps logged in. But I am doubting that this is a safe way to keep my user authenticated and do other actions. I tried looking up whether it is good to store it in cookies. But there are to many mixed reviews on this subject.
(the reason why I personally storing it in the cookies, is because nuxt3 is ssr and I wont be able to get the token if it was stored in the localstorage)
I know that cookies are more venerable to xsrf attacks and localstorage to xss attacks.
But what I understand when I am going to use the SPA authentication of laravel, those sessions and tokens are going to be saved in the cookies as well right? So what difference does that make with saving a token in the cookies?
TLDR: store it in the cookies + add some flags to it.
Here is my other answer, HTTPOnly and with Secure adds a layer of security to it.
And that one should probably be totally fine.
XSRF is something that should not happen on your website but if somebody got caught by phishing, you can't really protect the website more than that.
The security realm is a big thing, a system will never be bullet-proof: it's more of a matter of following the best practices as much as possible.
You can mitigate the damages but assigning a short TTL to your tokens and checking their viability on a middleware that runs on every client-side navigation.
I'm not an expert in security but you will probably not need one either. Follow that advice and consider your job done.
Social engineering + other breaches can lead to your website being breached in far easier ways.
If you are a big corporate company that needs those drastic security measures, you also have probably spent millions on ways to lock your network security up.
If your Laravel api(assuming you are using Laravel as API) and SPA(Nuxt) are on the same domain, You can use Sanctum cookie-based session authentication.
#1. Uncomment EnsureFrontendRequestsAreStateful middleware in app/Http/Kernel.php
'api' => [
\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
#2. Add SANCTUM_STATEFUL_DOMAINS in your .env file
SANCTUM_STATEFUL_DOMAINS=localhost:3000
#3. In config/cors.php, change support credentials to true
'supports_credentials' => true,
#4. Before you hit login endpoint make request to 'sanctum/csrf-cookie' and then POST request to login endpoint
// Sanctum endpoint to generate cookie
Route::get('sanctum/csrf-cookie', function () {
return response('OK', 204);
});
Route::controller(AuthController::class)->group(function () {
Route::post('auth/login', 'login');
});
#5. Enable the 'withCredentials' option on your application's global axios instance
axios.defaults.withCredentials = true;

What is the point of X-CSRF-TOKEN or X-XSRF-TOKEN, why not just use a strict same site cookie?

Frameworks such as laravel and others require you place the csrf token in your HTML forms.
However at the same time laravel comes by default with the VerifyCsrfToken middleware that automatically creates a X-XSRF-TOKEN cookie with the csrf token on every response. This cookie is used for ajax requests and is automatically added to the header for axios for example.
I am wondering why is it required to add the csrf token to every HTML form. Why could you not just use the already existing X-XSRF-TOKEN cookie to validate the csrf token. I understand there is the issue of same site cookies, and if your csrf cookie is set to lax or none the cookie would be sent from an external site if they would POST to my site. However this issue can be solved by setting the same site to strict then there would be no need to set the csrf token on every form which is kind of annoying to do and remember.
Is there some security concern I am missing on why we just cant use a strict cookie for validating the csrf token?
An X-CSRF-Token protects users against unwanted execution of modifying requests, which are of interest for their side effects (the changes which they make to the server, or the database), not for their response, which the attacker cannot read anyway, by virtue of the CORS protocol.
A same site cookie would protect even against execution of navigation requests, which do not change anything on the server, but only read data (including X-CSRF-Tokens for subsequent modifying requests), which is then displayed in an HTML page. For example, if stackoverflow.com had same site session cookies, you would not be able to navigate from your webmail site via a mailed link to this StackOverflow question and immediately click to upvote it, because the session cookie would not be included in the navigation request, therefore you would not be logged on at first.
SameSite cookies do indeed provide significant protection against CSRF attacks.
But it's always better to put an explicit counter-measure in place - that is provided by anti-CSRF tokens.
For one thing, SameSite uses a notion of "registerable domain" so it does not protect you against subdomain hijacking
Finally, for these topics I very much recommend an excellent book Api Security in Action - they discuss CSRF and related topics in Chapter 4.
there would be no point in validating csrf token through cookies. That's the problem we are trying to solve. If csrf token was sent and validated as a cookie, it also could be sent, and is sent in cross site request. But when doing cross site request, as far as I know, attacker can't read that cookie with js and put it inside the form, only we can access that cookie with js. That's because when we set a cookie we specify domain attribute, and that cookie can be read with js, only on that particular domain. That's the reason why that cookie is not http only, and why we include it inside forms.

Why Laravel user is logged out after redirecting back from payment?

I deployed my Laravel app to shared hosting (cpanel). For paying, the user first redirects to a bank account and then redirects to my page. during this procedure, the user gets logged out!
for protecting my routes I use auth middleware and for session driver, I use the default session driver which is file. also, the permission for framework/sessions is 777.
this is the code which redirect to the bank page:
$go = "https://thebank/example";
redirect()->to($go)->send();
and after a successful payment, the bank redirects to a route that I specified for verifying the payment.
Route::get('/payment/callBack' , 'PaymentController#VerifyData')->middleware('auth');
the route utilizes the auth middleware However most of the time the user is not logged in and automatically redirects to login page. I noticed if I don't use the auth middleware and if the user refreshes the page the user logs in automatically. this is not something that usually happens with laravel. I also tried the cookie driver for session and it didn't work and caused more problems.
I also didn't gain any success in storing user_id and cart_id in the default PHP $_SESSION. all SESSIONS seems to be cleared when user redirects back from the bank page.
how can I fix the problem?
The same_site setting is changed in default Laravel installation, make sure you change same_site to null in
config/session.php or callback won't include cookies and you will be logged out when a payment is completed. So inside your config/session.php update
return [
...
...
'same_site' => null,
...
...
];
I have configuration with this. But not working.
'secure' => env('SESSION_SECURE_COOKIE', false),
'same_site' => null,
If I set this
same_site' => "none"
Then it work
Solution for laravel 8-
In config/session.php
'secure' => true,
'same_site' => 'none'
Ref https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie
The new versions of the browsers might be logging you out because of the new cookie policy.
References
https://developers.google.com/search/blog/2020/01/get-ready-for-new-samesitenone-secure
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite
Whenever the cookie is required to be sent to server, the browser sees the SameSite attribute to decide if the cookie to be sent to server or blocked. For user actions, it is sent to the server but for auto-redirects, it doesn't if SameSite is set to 'Strict' or 'Lax' (Lax is going to be the default value now).
Solution:
The cookie attribute SameSite can be set to 'None' along with specifying the 'Secure' attribute to 'true'. Setting 'Secure' attribute to 'true' would require your site to run on https. Sites running with http:// protocol will not be able to set 'Secure' cookie.
Please set the 'HttpOnly' attribute to 'true' for making it accessible for http requests to the server only.
In PHP, it can be achieved as below
session_set_cookie_params(0, '/PATH/; SameSite=None', <COOKIE_DOMAIN>, true, true);
It is one of my very old questions that I figured out myself but forgot to share the solution. However, I see this page is still active I decided to share my solution.
My problem actually was the protocol of redirecting URL. My mistake was that I set the redirect URL of '/payment/callBack' to http. While my website was https. The sessions for https and http are different, so user logged in https can not be logged in to http. my solution was first corrects the URL callback to https version. and set the nginx config to redirect all http to https.
I solved this issue by adding an API route for callback. Inside controller you can redirect or return view.

laravel Api Resource. Delete Request Session expired. Only Get method Working

Eloquent: API Resources
I am Trying to Crud a table using POSTMAN and laravel Api Resources. ]
Although using get method i can get all the data. When i use delete or post method, it returns an error of session expired.
Thanks in advance.Image Of POSTMAN
Image of routes
Sounds like you're missing the CRSF token, which would explain why HTTP GET's are working. One option to work around this is to disable the CSRF middleware when working in your development environment. Simplest solution is to open up app/Http/Middleware/VerifyCsrfToken.php and set:
protected $except = [
'*',
];
The * is a wildcard-like option that will disable CSRF verification for all routes. Obviously ideal solution would to be to disable it on a higher level only when working on local development, but the provided answer is a quick solution.
See the Laravel documentation on CSRF Excluding URI's
Sorry for the trouble. I found the problem,actually i was posting the routes in web.php instead of api.php . That was why i was getting the errors. Thankyou for the concern.

Codeigniter CSRF problem: CSRF request and response token mismatch

I spend a lot of time searching for the solution for this problem, but with no luck so I am hoping somebody can help me.
I enabled CSRF protection and set csrf_regenerate to true (I want to regenerate the CSRF token on each request).
I am testing with my login form. The problem occurs when first submit the form with invalid data and the refresh the page (F5). I get thew error: The action you have requested is not allowed, so the CSRF token validation failed.
I noticed that when submitting the form with invalid data, CSRF request and response tokens do not match and I thing that is the cause of the problem.
I am guessing I'm not the first one with this problem, so I really hope somebody can help me out.
I you need any additional data please let me know.
Thanks and regards, Gregor

Resources