Adding Access-Control-Allow-Origin to Laravel - laravel

The app in question (I am simply trying to maintain/bug fix - I am not the author) (Laravel 5.1.7) needs to call JavaScript located at s7.addthis.com. This is currently not working and is returning a Cross-Origin Request Blocked error. After doing some research, I found barryvdh/laravel-cors which seems to be the preferred method for addressing this problem. However, I believe that I have followed all of the instructions, but the Access-Control-Allow-Origin is not appearing in the output.
These are the steps I followed (I am a Laravel novice...):
composer require barryvdh/laravel-cors 0.7.x
composer update
cp vendor/barryvdh/laravel-cors/config config (did not customize)
Added 'Barryvdh\Cors\ServiceProvider', to the $providers array in config/app.php
Added 'Barryvdh\Cors\HandleCors', to the $middleware array in app/Http/kernel.php
php artisan vendor:publish --provider="Barryvdh\Cors\ServiceProvider"
The header is still not being added to the output, i.e., the errors persists. What step did I miss and/or what did I do wrong?
In an attempt to just things working, I tried adding the following to the top of bootstrap\app.php
// allow origin
header('Access-Control-Allow-Origin: *');
// add any additional headers you need to support here
header('Access-Control-Allow-Headers: Origin, Content-Type');
but this too had no effect.
I did see this post: http://en.vedovelli.com.br/2015/web-development/Laravel-5-1-enable-CORS/, which looks straight-forward enough, but in my app, the javascript is called in this manner: {!! Html::script('//s7.addthis.com/js/300/addthis_widget.js#pubid=xxx', array('async' => 'async')) !!} and I do not know how to cast this into the form shown.
Thank you.
In response to SSahut:
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
'Barryvdh\Cors\HandleCors',
];

Related

Laravel 9 419 Unknown Status on sending POST request

Good day, I'm having trouble on sending post data to my Laravel project, It always shows Page Expired (419) on this,
Error 419 on POST
Here's the things I have done before coming up to my question:
Added SESSION_SECURE_COOKIE=FALSE on .env
Changed the config/session.php from 'secure' => env('SESSION_SECURE_COOKIE'), to 'secure' => env('SESSION_SECURE_COOKIE', false),
Added ob_start(); at the beginning of public/index.php like this <?php ob_start(); use Illuminate\Contracts\Http\Kernel; use Illuminate\Http\Request;
This is my route
Route::post('/data', [AdminController::class, 'getSensorData']);
Also in I'm sending the data to the database from the post request using the controller.
The request works fine when the method is GET.
200ok on GET
Edit: It's working now, the fix was from #Ahmed Hassan. Thank you.
this issue occur because you didn't send the CSRF token with the request
just add #csrf inside your form and it will work
also, you can exclude your URL in the $except list in the App\Http\Middleware\VerifyCsrfToken
I hope it's helpful

Load test Laravel application with jmeter

I am trying to load test a Laravel application, however I'm stuck at the very beginning. I am attempting a login with a POST request, but I'm always getting response code: 419. I have googled and asked around a bit to no avail.
So far, I have extracted the xsrf token from the GET request and am trying to append it as a header to the POST request. I'm not sure if I'm doing it correctly, however.
That's what my header manager looks like, I looked at the post request through dev tools when doing it manually and I tried to replicate it.
I really can't tell what I'm doing wrong. I don't think I can fix this by using a different tool.
For web routes you need to Disable CSRF, or put csrf on the jmeter.
For API routes you need to disable rate limiter. Just go to app/Http/Kernel.php and comment throttle:60,1 line
protected $middlewareGroups = [
...
'api' => [
// 'throttle:60,1',
],
];
Maybe you should disable these on test environment only, in most cases in the production these feature is needed.

CORS issue with laravel rest api POST

Failed to load https://example.com/api/api_details: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://example-international.firebaseapp.com' is therefore not allowed access.
That is my error when requesting a POST method. But its perfectly alright when it was in local and i put these line in header on laravel function:
header('Access-Control-Allow-Origin: *');
I also tried these for online:
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE, PUT');
But no luck. All the post and get request are okay in local but in online only get request works. I am using angular 6 and laravel 5.3.
here is my network tab given bellow:
Use this package inside your Laravel application.
https://github.com/barryvdh/laravel-cors
It's very simple and will solve your problem.
Just don't forget to publish the config file using:
$ php artisan vendor:publish --provider="Barryvdh\Cors\ServiceProvider"
create a cors middleware and replace your handle method with
public function handle($request, Closure $next)
{
return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
->header('Access-Control-Allow-Headers', 'Accept, Authorization, Content-Type');
}
Building web applications with Microservices Architecture comes with a couple of fixable issues. One of such issues is CORS. Most commonly, you face this issue when you try to test decoupled applications locally on your machine.
Say we had a RESTful API built with Laravel and a SPA built with VueJS, attempting to make a request from the Vue App running on port 8080 to the Laravel backend running on PORT 8000 might lead to an error like such:
[Check Error:][1]
[1]: https://i.stack.imgur.com/rGMmS.png
Thankfully, we can fix this easily in Laravel with the Laravel-cors package.
Installation
The Laravel-Cors package can be installed using composer. Navigate to your Laravel application folder in the terminal and run:
composer require fruitcake/laravel-cors
Configuration
After a successful installation, you should now have the Laravel-cors package added to your packages, you can check that you have it in your composer.json file.
"fruitcake/laravel-cors": "^1.0",
Next, we’ll need to add the HandleCors middleware in the $middleware property of app/Http/Kernel.php class. Open app/Http/Kernel.php and add this line in the $middleware property.
protected $middleware = [
...
\Fruitcake\Cors\HandleCors::class, # this line
];
Finally, we need to publish the package so the configuration file can be copied from the package directory to our application directory.
php artisan vendor:publish --tag="cors"
A new file (config/cors.php) should be added to your config folder. This file should contain default configurations for CORS. You can use the default configuration or tweak it however you wish. Let’s dig in a bit and see what options this file provides us.
<?php
return [
'paths' => [],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => false,
'max_age' => false,
'supports_credentials' => false,
];
paths: This option takes an array value and allows us to enable cors for multiple paths. Some example configurations would be:
'paths' => ['api/*', 'api/admin/*', 'api/users/*', '*']
allowed_methods: This option indicates what HTTP request methods to allow on the specified paths. [*]allows all methods. Some examples of option values would be:
'allowed_methods' => ['POST', 'GET', 'DELETE', 'PUT', '*']
allowed_origins: This option specifies what source requests should be allowed from. If you would want to test from your local machine, you would have to add “localhost” + the port to the list of allowed origins.
'`enter code here`allowed_origins' => ['http://localhost:8080', 'https://client.myapp.com']
allowed_origins_patterns: This option matches the request origin with patterns.
'allowed_origins_patterns' => ['Google\']
allowed_headers: This option is used to set the Access-Control-Allow-Headers, which is used in response to a preflight request which includes the Access-Control-Request-Headers to indicate which HTTP headers can be used during the actual request.
'allowed_headers' => ['X-Custom-Header', 'Upgrade-Insecure-Requests', '*']
exposed_headers: This option is used to set the value of Access-Control-Expose-Headers response header. This response header indicates which headers can be exposed as part of the response by listing their names.
max_age: This option is used to set the Access-Control-Max-Age response header. The Access-Control-Max-Age response header indicates how long the results of a preflight request ( the information contained in the Access-Control-Allow-Methods and Access-Control-Allow-Headers headers) can be cached.
supports_credentials: This option sets the Access-Control-Allow-Credentials header. The Access-Control-Allow-Credentials response header tells browsers whether to expose the response to frontend JavaScript code when the request's credentials mode (Request.credentials) is included.
Now we have an understanding of the function of each of the options. You can configure these options however you want. Once you’re done, you want to reload your Laravel configurations and allow your changes to reflect.
php artisan config:cache
This should clear your configuration cache and recache the updated configurations (including your changes). From here you can serve your application.
php artisan serve
I hope this post helps you resolve any of your Laravel CORs issues.
Cheers 🍻

Driver [provider] not supported laravel/socialite

I'm using Laravel 5.4 and Socialite 3.0
With every new socialite provider I add I get the error:
Driver [provider] not supported.
for example when adding socialiteproviders/twitch 3.0 I will get the error:
Driver [twitch] not supported.
However I can use a provider that's already built in to Socialite, github for example works as expected.
I have tried three different providers and I get the same result each time, what am I doing wrong?
Here are my routes:
Route::get('/auth/bnet', 'BnetController#redirectToProvider');
Route::get('/auth/bnet/return', function() {
$user = Socialite::driver('battlenet')->user();
dd($user->accessTokenResponseBody);
});
Route::get('/auth/git', function() {
return Socialite::driver('github')->redirect();
});
Route::get('/auth/twitch', function() {
return Socialite::with('twitch')->redirect();
});
Here's my $listen from my EventServiceProvider:
protected $listen = [
\SocialiteProviders\Manager\SocialiteWasCalled::class => [
// add your listeners (aka providers) here
//'SocialiteProviders\Battlenet\BattlenetExtendSocialite#handle',
'Reflex\SocialiteProviders\BattleNet\BattleNetExtendSocialite#handle',
'SocialiteProviders\Twitch\TwitchExtendSocialite#handle',
],
];
I have added SocialiteProviders\Manager\ServiceProvider::class, to my providers array in app.php, I have added the Socialite facade ('Socialite' => Laravel\Socialite\Facades\Socialite::class,) to my aliases array also in app.php and have added the appropriate keys to my .env
I had the same issue and I found solution.
In config/app.php providers array:
'providers' => [
// ...
Laravel\Socialite\SocialiteServiceProvider::class,
\SocialiteProviders\Manager\ServiceProvider::class,
// ...
]
In app/Providers/EventServiceProvider.php:
protected $listen = [
// ...
\SocialiteProviders\Manager\SocialiteWasCalled::class => [
'SocialiteProviders\VKontakte\VKontakteExtendSocialite#handle',
],
]
You missed \ at start of 'SocialiteProviders\Twitch\TwitchExtendSocialite#handle'.
Hopefully this helps someone, but I found that I had to separate the EventServiceProvider.php listen classes with "\\" instead of "\". Laravel 5.6. e.g:
protected $listen = [
\SocialiteProviders\Manager\SocialiteWasCalled::class => [
'SocialiteProviders\\Twitch\\TwitchExtendSocialite#handle',
'SocialiteProviders\\Podio\\PodioExtendSocialite#handle',
],
If you're still struggling, triple-check to ensure all of the packages are installed.
I also found that including...
Laravel\Socialite\SocialiteServiceProvider::class,
...in your config/app.php is not necessary when using SocialiteProviders\Manager.
Make sure that you have updated config/services.php to include the client_id client_secret and redirect from your provider.
Clear your config and try again.
Adding an answer here because this question comes up while searching for the same error as it pertains to Lumen as well and I suspect others may run into the same issue that I did.
The Lumen-specific documentation for additional providers doesn't appear to mention some gotchas (at least, for my version of Lumen) and Lumen needs a little extra configuration to work compared to Laravel.
I'm on Lumen 5.8.2 and had been becoming increasingly frustrated getting Socialite with additional providers set up - all of my configuration in bootstrap/app.php and EventServiceProvider.php seemed correct (and was) until I realized that Lumen wasn't actually registering the EventServiceProvider itself.
To remedy this problem, register the EventServiceProvider within your bootstrap/app.php setup:
$app->register(App\Providers\EventServiceProvider::class);
With the EventServiceProvider registered, just refer to the other answers here to configure events, the provider's service config and registering Socialite in app.php and you ought to be good to go.
I had the same issue, to solve it i change the order of my bootstrap/app.php config, try moving the next lines after the Event ServiceProvider:
$app->register(\SocialiteProviders\Manager\ServiceProvider::class);
class_alias(Laravel\Socialite\Facades\Socialite::class, 'Socialite');
//$app->register(Laravel\Socialite\SocialiteServiceProvider::class);
After:
$app->register(App\Providers\EventServiceProvider::class);
My issue was because i declared all the Socialite and SocialiteProvider stuff before.

Why is my CSRF token empty when using Form::open()?

I am just starting out so please forgive me. I have a solid grasp on CodeIgniter, so I understand what is going on. However, I am noticing that my CSRF token is empty when I am creating a form. I am working through the laracasts videos to get a gasp on Laravel workflow.
myfile.blade.php
{!! Form::open((array('action' => 'MyController#method'))) !!}
...
{{!! Form::close() !!}}
Here is what I am getting when I view the source:
<form method="POST" action="http://mysite.dev/route" accept-charset="UTF-8">
<input name="_token" type="hidden">
</form>
I've looked through the config directory, but see nothing on having to enable csrf. Is there an additional setting somewhere I need to update?
Thank you for your suggestions.
EDIT
Even this gives me an empty hidden input field:
{{ Form::token() }} // <input name="_token" type="hidden">
EDIT
Here is what my controller looks like:
//use Illuminate\Http\Request;
use Request;
use App\Article;
use App\Http\Requests;
use App\Http\Controllers\Controller;
public function store(Request $request)
{
$input = Request::all();
return $input;
}
So my updated form tag looks like this:
{!! Form::open((array('action' => 'ArticleController#store'))) !!}
...
When I submit, I can see the json response - the token is obviously empty.
{"_token":"","title":"test","body":"test"}
The Laravel Fundamental series is for Laravel 5.0 so you have a few options. You can install Laravel 5.0 to continue with that series. In order to install L5.0, you need to run this command:
composer create-project laravel/laravel {directory} "~5.0.0" --prefer-dist
If you want to use Laravel 5.2 though (which I would recommend and Jeffrey Way will most likely release a series on this soon), there are several extra things to take into consideration.
First, put all your routes inside a "web" middleware group like this:
Route::group(['middleware' => ['web']], function () {
// Put your routes inside here
});
In the past, there were several middlewares that ran on every request by default. In 5.2, this is no longer the case. For example, the token is stored in the session, but in 5.2, things like the "StartSession" middleware are not automatically applied. As a result, the "web" middleware need to be applied to your routes. The reason for this change in 5.2:
Middleware groups allow you to group several route middleware under a single, convenient key, allowing you to assign several middleware to a route at once. For example, this can be useful when building a web UI and an API within the same application. You may group the session and CSRF routes into a web group, and perhaps the rate limiter in the api group.
Also, in the Laravel Fundamental series, Jeffrey pulls in the "illuminate/html" package, but now, most people use the laravel collective package. They handle a lot of the Laravel packages that are taken out of the core. As a result, I would remove the "illuminate/html" package. In your composer.json file, remove "illuminate/html: 5.0" (or whatever is in the require section). Also, remove the corresponding service provider and form facades that you added to your config/app.php file.
To install the laravel collective version, add this in your composer.json file instead: "laravelcollective/html": "5.2.*-dev". Then, run composer update. Once that's done, in your config/app.php file, add this to your providers array:
Collective\Html\HtmlServiceProvider::class,
and add this to your aliases array:
'Form' => Collective\Html\FormFacade::class,
'Html' => Collective\Html\HtmlFacade::class,
I hope I'm not missing anything else.
This is a config issue .You need to set the app key in your config file ...config/app.php to a 32 character string or use artisan cli php artisan key:generate to genearte the key for you to be able to use the CSRF token .
Also make sure that you include routes that use the CSRF token in the web group route .
You may exclude URIs by defining their routes outside of the web middleware group that is included in the default routes.php file, or by adding the URIs to the $except property of the VerifyCsrfToken middleware: http://laravel.com/docs/5.2/routing#csrf-protection
If you have a login page and you want to clear out the session using:
Session::flush();
Don't forget that this also cleans out the csrf token before it can be put in the view
It should be
{!! Form::open((array('action' => 'MyController#method'))) !!}
...
{!! Form::close() !!}
I have solved the issue of HtmlService provider actually 5.2 version removed Illuminate and add collective follow the step to solve the issue:
composer require laravelcollective/html
composer update
add in config/app.php
'providers' => ['Collective\Html\HtmlServiceProvider'],
'aliases' => [
'Form' => 'Collective\Html\FormFacade',
'Html' => 'Collective\Html\HtmlFacade',
],
Then you are able to use that form.

Resources