TokenMismatchException in VerifyCsrfToken.php line - laravel

i am using laravel 5.1 its working on localhost but not working on server getting error
TokenMismatchException in VerifyCsrfToken.php line 53:
here is my code link
https://www.itextpad.com/XMkKhqCnof
help me

You must have (usually hidden) CSRF token field as part of your form, so just add
{{ csrf_field(); }}
somewhere in your form, and Laravel will do the rest.
https://laravel.com/docs/5.5/csrf

Make sure your admin.blade.php layout has this meta tag on its head:
<!-- CSRF Token -->
<meta name="csrf-token" content="{{ csrf_token() }}">
Hope this helps you.

Since you are using Form builder remove this from your form. Laravel form builder automatically adds a hidden token field to your form when you do Form::open()
<input type="hidden" name="_token" value="{{ csrf_token() }}">

If you want to use CSRF token in javascript what we mainly recommend is to put on meta and call from meta which this will come together with laravel 5.3 and above.
<meta name="csrf-token" content="{{ csrf_token() }}">
how to use it ?
if you are using 5.3 or above you can just use token to get the csrf_token that is not a magic you can see laravel have declare it in bootstrap.js with this code
let token = document.head.querySelector('meta[name="csrf-token"]');
if you are below ver. 5.3 can use the code above to get csrf token also
and also maybe the problem is not from the csrf token I suspect it is your javascript from data is not working try to use new FormData() instead hope thats help.
for more about form data can look at
here and here

Related

Export Excel with Laravel, VueJS and Inertiajs

I'm trying to build and application on Laravel, VueJS and inertiajs.
I'm using maatwebsite/excel to export my data into excel format.
I've a vue component which has a normal HTML form
home.vue
<form action="/project-profile" target="_blank" method="POST" enctype="multipart/form-data">
<input type="hidden" name="_token" :value="csrf.content" />
<input type="hidden" name="slug" :value="JSON.stringify(generalDetails.slug)" />
<button class="font-medium tracking-wide">Download Profile</button>
</form>
And on mounted method I'm just placing my csrf token.
mounted() {
this.csrf = document.head.querySelector('meta[name="csrf-token"]');
}
In Laravel part I made a route in web.php file
Route::post('project-profile','ProjectProfileExportController#ProjectProfile');
Whenever I try to export or submit the form, I get page expired error, I followed few guide and it says there is issue with csrf_token but while inspecting the form I can see token is placed appropriately.
I tried doing the same by making this as api, api.php:
Route::post('project-profile', 'ProjectProfileExportController#ProjectProfile');
But this thing also not work as expected.
Screenshot of page expired screen
Screenshot of inspect form element
Any better approach is welcome. Thanks.
Creator of Inertia.js here.
So, we recommend not manually sending the csrf token on each request like this.
A better approach is to use the CSRF functionality already built into axios for this. Axios is the HTTP library that Inertia uses under the hood.
Axios automatically checks for the existence of an XSRF-TOKEN cookie. If it's present, it will then include the token in an X-XSRF-TOKEN header for any requests it makes.
The easiest way to implement this is using server-side middleware. Simply include the XSRF-TOKEN cookie on each response, and then verify the token using the X-XSRF-TOKEN header sent in the requests from axios.
Some frameworks, such as Laravel, do this automatically, meaning there is no configuration required. So, I'd recommend removing the csrf-token meta tag from your template, and removing the _token from your requests. That should take care of your issues.
That all said, keep in mind that you will not be able to download an Excel file from an Inertia request. All Inertia requests MUST return a valid Inertia response. You can use window.open for this. Something like this:
window.open(`/url/to/excel/download?slug=${generalDetails.}`, '_blank')

Laravel - 419 issues when Submit Form

I have problems when submitting a form in Laravel application. It reported 419 error.
My code:
<form action="login" method="POST">
<input id="csft_pass" type="hidden" name="_token" value="{{ csrf_token() }}">
.....
</form>
I tried fixing it:
<form action="login" method="POST">
#csrf
.....
</form>
But still, error 419
With the above code still running normally, suddenly there was an error today
I tried many ways like php artisan cache:clear but still not solve the issue.
My Laravel version: 5.8
UPDATE: I tried a lot of solutions on stackoverflow but still can't solve it. I think that because the application's session has something wrong
After form tag use csrf_field.
{{ csrf_field() }}
And if you are using ajax you may pass csrf token on meta tag like.
<meta name="csrf-token" content="{{ csrf_token() }}">
You can use the csrf_field helper to generate the token field:
<form method="POST" action="/login">
#csrf
...
</form>
OR
<input type="hidden" name="_token" value="{{ csrf_token() }}">
It doesn't work, then Refresh the browser cache and now it might work.
Why required: Refresh the browser cache
When we update our application, a browser may still use old files. If you don’t clear your cache, Old files can access problems when you apply.
For more details open link :- Error - 419 Sorry, your session has expired
With the above code still running normally, suddenly there was an error today
This makes me suspect the error occurs only when the form was opened for more than two hours (that's the default of lifetime in config/session.php) before submitting.
If that's the case, you could set a value of more than 120 minutes as lifetime or do something in frontend to keep the session alive, such as some custom JavaScript (for single forms) as described in the selected answer to this thread or Laravel Caffeine (for whole apps)
Replace these lines
<input type="hidden" name="_token" value="{{ csrf_token() }}">

How to use default csrf-token from AJAX request in Laravel

I'm using Vuejs and I want to make an secure AJAX request (with axios) to my laravel server, but I think that CSRF protections doesn't work because I change the token of the frontend part and even then I can interact with the database.
I read that Laravel come with a file named [bootstrap.js] (https://laravel.com/docs/5.8/csrf#csrf-introduction) it is assumed that this file does this task by default, but it doesn't work for me. I think it's beacuse webpack doens't load the file when I run npm run watch but I don't know how to load it,
I searched for an answer but I only find Bootstrap tutorials :/
In head:
<meta name="csrf-token" content="{{ csrf_token() }}">
In ajax:
window.axios = require('axios');
window.axios.defaults.headers.common = {
'X-CSRF-TOKEN' : document.querySelector('meta[name="csrf-token"]').getAttribute('content');
};
You can put the CSRF in the meta as _token. Like this:
<meta name="csrf-token" content="{{ csrf_token() }}">
Visit the laravel documentation for this.
https://laravel.com/docs/5.6/csrf#csrf-x-csrf-token
And then access it in your javascript.
You should add VerifyCsrfToken middleware for the API group
(app/Http/Kernel.php)

CSRF error in laravel

I have a problem in Laravel . when over and over submit Form with post method and somtimes I get error and see expire error that related to CSRF
anybody knows how can I manage this error that display not in site and instead of redirect to any page else ?
Laravel makes it easy to protect your application from cross-site request forgery (CSRF).
Just add #csrf blade directive inside the form to avoid getting csrf token error.
<form method="POST" action="/profile">
#csrf
...
</form>
The directive puts something like this
<input type="hidden" name="_token" value="CzK6peomC6Pnnqdm4NsxpdGSH6v1evDnbN12oL" >
Read more about it in the laravel documentation here https://laravel.com/docs/5.6/csrf
Regarding the expiration of the token I think you might want to handle the error this way https://gist.github.com/jrmadsen67/bd0f9ad0ef1ed6bb594e
Also, there's a package which helps the forms keep awake.
https://github.com/GeneaLabs/laravel-caffeine
I hope that helps.
Laravel 5 using Blades templates, it's easy.
Add csrf toke in your blade file
{{ csrf_token() }}
If you are using Laravel 5.6 then you need to add something like this in your code of the form
#csrf
Check in detail about: CSRF Laravel

Mixed Content (laravel)

I get the following error (on every page)
app.js:703 Mixed Content: The page at 'https://sitename.com/' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://sitename.com/index.php/getMessages'. This content should also be served over HTTPS.
The site is build with Laravel.
Is there anybody who knows how to fix this error?
In my case it's because I wasn't aware that the asset() function didn't handle https automatically (as pointed out by frankfurt-laravel's answer).
To get around this, since I don't use SSL in dev, I set ASSET_URL in the .env to the https url:
APP_URL=https://example.com
ASSET_URL="${APP_URL}"
This overrides the asset() function to use the https url, without having to modify the function at all. See the docs for more context.
If you are moving the website from HTTP to HTTPS, and it's was working perfectly on HTTP, and if you have added the new URL with https in config/app.php and also in the .env file then you may need to add the below snippet in your app/Providers/AppServiceProvider.php file's boot function and do not forget to add "use Illuminate\Support\Facades\URL;" at the top of the file to fix this error.
Please check attached for better sample code
use Illuminate\Support\Facades\URL;
public function boot()
{
URL::forceScheme('https');
}
I had same problem few days ago. Do you use Cloudflare? Change flexible SSL to Full.
I suggest to use the method argument $secure Laravel (5.6 has it definitely) provides:
When you use asset loading, e.g.
<!-- Scripts -->
<script src="{{ asset('js/app.js') }}" defer></script>
<!-- Styles -->
<link href="{{ asset('css/app.css') }}" rel="stylesheet">
You can lookup the definition for asset(), if you have some kind of advanced IDE. If not, please check this file helpers.php.
However, the documentation says
/**
* Generate an asset path for the application.
*
* #param string $path
* #param bool $secure
* #return string
*/
So you just need to pass true as the second argument, and then the resource is loaded in a secure way. For above examples it would be
<!-- Scripts -->
<script src="{{ asset('js/app.js',true) }}" defer></script>
<!-- Styles -->
<link href="{{ asset('css/app.css', true) }}" rel="stylesheet">
Please note, this will cause conflict if you use php artisan serve, as artisan is not capable to serve via HTTPS protocol. Thus you need HTTPS setup e.g. with Valet on MacOS or Homestead on Windows. Follow the links for setup details.
Hope this helps, please let me know if it worked.
Make sure to remove trailing slashes from XMLHttpRequest endpoint URL.
If you are using Laravel Octane, I figured the fix by looking at octane.php config file.
Set your env to let octane inform upstream framework to use HTTPS.
OCTANE_HTTPS=true
Fixed the issues I was having with mixed-content and email verification signature failure.
In your .env file set your url to https APP_URL=https://sitename.com and in your config/app.php set url to 'url' => env('APP_URL', 'APP_URL=https://sitename.com'), that should solve your problem
I'm using Laravel 8 and Livewire 2. I created the app on Digital Ocean and to fix those issues, I had to do it like this:
<!-- Tailwind CSS -->
<link href="{{ secure_asset('css/app.css') }}" rel="stylesheet">
<!-- Alpine -->
<script src="https://cdn.jsdelivr.net/gh/alpinejs/alpine#v2.x.x/dist/alpine.min.js" defer></script>
<!-- Scripts -->
<script src="{{ secure_asset('js/app.js') }}" defer></script>
#livewireStyles
I had to used secure_asset instead. That's on the Laravel Documentation.
I also had to change all "route" references for secure_url like this:
<form method="POST" action="{{ route('logout') }}">
<form method="POST" action="{{ secure_url('/logout') }}">
Hopefully this will help.
You opened the page 'https://sitename.com/' . But the javascript of this page sent an http request, not https.
You should change your javascript code to send https request.
There are two ways to send https request:
Put the protocol together with path.
$.get('http://sitename.com/index.php/getMessages')
Ignore the protocol, but put '//' before the path
$.get('//sitename.com/index.php/getMessages')

Resources