How to use default csrf-token from AJAX request in Laravel - 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)

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')

Not able to load logo on the web

Hope you can clarify this issue:
I am trying to ad a favicon to my website in the head of my html layout, the link i am using is :
href="{{ asset('assets/public/images/favicon-32x32.png') }}"
I have my file in the following route:
backend/public/images/icon.png
the icon is not displaying on the web anyway, any idea about what can be the issue here?
thanks
as in laravel documentation
The asset function generates a URL for an asset using the current
scheme of the request (HTTP or HTTPS):
$url = asset('img/photo.jpg');
You can configure the asset URL host by setting the ASSET_URL variable
in your .env file. This can be useful if you host your assets on an
external service like Amazon S3:
// ASSET_URL=http://example.com/assets
$url = asset('img/photo.jpg'); // http://example.com/assets/img/photo.jpg
so if you use default ASSET_URL value in .env file and your favicon file in file structure like :
project_Folder/public/images/favicon.ico
so you need to make your link like
{{-- favicon --}}
<link rel="shortcut icon" href="{{ asset('images/favicon-32x32.png') }}">

css not working after passing id in url in laravel 5.6

My CSS is not working after passing an ID in an URL in Laravel 5.6
My route
Route::any('productdetail/{id?}','AdminController#productdetail');
The ID URL
<i class="icon-eye"></i>
I am using Laravel 5
This is the script tag:
<link rel="stylesheet" href="{{URL::asset('/css/style.css')}}">
Just use what #demo suggested.
asset('/css/style.css')
Or just
href="/css/style.css"
But never
href="../css/style.css"
Because if you later on change your current URL from 127.0.0.1:8000/productdetail/{id} to , let's say, 127.0.0.1:8000/productdetail/something/{id}, the asset will not be loaded properly anymore.
By using "/" in front of a source, you are telling the browser to start looking from the base URL, which is 127.0.0.1:8000/ in your case.
By omitting "/" in front of a source you are telling the browser to start looking from the current URL, which would be 127.0.0.1:8000/productdetail in your case, or even 127.0.0.1:8000/productdetail/{id} when you add your ID to it.
This problems occurs because we are using the relative path in our blade template and the solution is so simple, We have to use only the asset function to overcome this problem.
So change your code like this:
<link href="{{ asset('css/bootstrap.min.css') }}" rel='stylesheet' type='text/css' />
<script src="{{ asset('js/jquery.min.js') }}"> </script>

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')

TokenMismatchException in VerifyCsrfToken.php line

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

Resources