connecting laravel and ionic fix access origin - php

Here the code I have used to fix access origin problem in ionic.
I have already tried cors package in laravel. need to do this in laravel using middleware.
here is my pure php code.
if (isset($_SERVER['HTTP_ORIGIN'])) {
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // cache for 1 day
}
please help me to do above using laravel.

I also suffered from the same problem of linking ionic with laravel and solved it using the package barryvdh/laravel-cors.
I allowed the cors.php file published by the package to allow the origins which the ionic apps will be hitting from but you can also set the config as follows to be allowed by all origins in the file
'supportsCredentials' => false,
'allowedOrigins' => ['*'],
'allowedHeaders' => ['*'],
'allowedMethods' => ['*'],
'exposedHeaders' => [],
'maxAge' => 0,

Related

Laravel Sanctum Angular Authentication 419 error code

I'm trying to setup an authentication system using Laravel Sanctum and Fortify for the back-end and Angular for the front-end.
The front-end is running on localhost:4200
the back-end is running on: localhost:8000
I followed this tutorial for the common mistakes and set the .env file accordingly
so it looks like this:
SESSION_DRIVER=file
SESSION_LIFETIME=120
SESSION_DOMAIN=localhost
SANCTUM_STATEFUL_DOMAINS=localhost:4200
FRONTEND_URL=http://localhost:4200
and so is my cors.php configuration:
<?php
return [
'paths' => ['*'],
'allowed_methods' => ['*'],
'allowed_origins' => [env('FRONTEND_URL', 'http://localhost:4200')],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => true,
];
For logging in my users I'm using this angular service function:
options = {
headers: new HttpHeaders({
Accept: 'application/json',
}),
withCredentials: true,
}
login(email: string, password: string): Observable<any> {
return this.http
.get(this.baseUrl + '/sanctum/csrf-cookie', this.options)
.pipe(
switchMap(() =>
this.http.post(
this.baseUrl + '/login',
{ email, password },
this.options
)
)
);
}
the problem is that when I try to login I get back a 419 erro code saying that the CSRF token mismatches.
taking a look at the cookies inside the browser's console the list is empty so no cookies are passed even if the request to /csrf-cookie is successfull
What am I doing wrong her? is it the angular service or my back-end config?
I finally solved the problem after asking on every possible source, let's talk about it:
Looks like that specifically on MacOS, if you try to send a request from localhost:4200 Origin and Refero headers will not match the Host header for some reason
i solved this changing every localhost occurrence in my Laravel .env and config files and then going to 127.0.0.1:4200 inside the browser instead of localhost:4200
it's a bit weird to explain but it makes requests come to the same source even if the localhost keyword should mean 127.0.0.1 IP by default
hope this will help someone

Having cors problem with sub-sub domain to sub domain

Never understood what is the main problem with cors while I allow everything (use * on everything). I have stancl/tenancy, using singledb approach and have online dev server with username as subdomain as my working folder.
So I need to use second level sub domain as tenantOne . soix . example . com.
Anyway, I am using laravel splade package and it contains filepond package for file picker. Upload works good however when it prepends existing file to preview it is using first level subdomain as main domain from second sub domain as tenant. Which gets me this error:
Access to XMLHttpRequest at 'https://soix.example.com/storage/files/1/blog-posts/11/v7f80bOhp0bXWrkHMYiRTq5IHF9jw4doqSrtZFDA.jpg' from origin 'https://tenantOne.soix.example.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
And my cors file contains:
'paths' => ['*'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => false,
Any help here?
Tried allowing everything on cors and separately for each tenant, didn't work. (Ofc cleaning cache)
Currently, I found a workaround since I can't get cors to work at all:
if (tenant()) {
Config::set('filesystems.disks.public.url', route('tenant.index') . '/storage');
}
So it uses sub-domain as main URL

Laravel CORS -Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested

I am trying to integrate Laravel socialite to my project, i am coming across the following error
Access to XMLHttpRequest at 'https://github.com/login/oauth/authorize?client_id=6b87b76a942a90caec24&redirect_uri=http%3A%2F%2Flocalhost%3A8000%2Fgithub%2Fcallback&scope=user%3Aemail&response_type=code&state=ZLzrBzsFH6YVKpat3yZ5a2G6vLd0wWedFRwFRXoc' (redirected from 'http://localhost:8000/github') from origin 'http://localhost:8000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
The issue is when i press sign in with github button i get the above error
Error Picture
cors.php file
'allowed_methods' => ['*'],
'allowed_origins' => ['http://localhost:8000'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => false,
am using the Fruitcake/laravel-cors package
protected $middleware = [
\Fruitcake\Cors\HandleCors::class,
];
Where am i going wrong?
Access to XMLHttpRequest at 'https://github.com/...' (redirected from 'http://localhost:8000/github') ... blocked by CORS policy
You are not Github.
The code running on your Laravel application is not running on github.com.
You cannot grant permission to your JavaScript to read data that Github is sending to the user's browser.
In broader terms, you've gone very wrong somewhere in your attempt to implement OAuth. You are making an Ajax request where you need to make a request that navigates the browser to Github for the user to interact with their login UI.

Laravel CORS Missing Allow Origin

i have issue with Laravel CORS (Laravel 8.54). I have installed fruitcake/laravel-cors in my project, and also i have resgitered it in kernel.php.
The config/cors.php is look like this:
'paths' => ['api/*', 'sanctum/csrf-cookie'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => false,
The provblem is, when i try access API from post, it is clear no problem, but when i try access API from my reactJS project that using axios (0.21) for http client, the response is always CORS Missing Allow Origin. I tried to access other API from my reactJS project and it is clear no problem.
Anyone know how to fix this? Thank you in adcance.

Allowing cors in artisan serve

Now after starting to learn Angularjs and Laravel 4 I just love the way one can just set up a working development server with just one terminal command without having to set up virtualhosts or anything like that.
However...
I want to develop my frontend seperately so I can utilize the wonderful combination of yeoman and gruntjs and since I really can't do this if I put everything in laravel public folder (or at least I don't know how) this leaves me with the following situation:
I have a frontend grunt server at localhost:9000
And
I have a laravel 4 server at localhost:8000
This will of course mean that in order for Angularjs to talk with Laravel I have to allow CORS. In Apache this is easy: just adding Header add Access-Control-Allow-Origin "localhost:9000" to the directory part of httpd.conf allows this url to communicate with localhost.
Now where should I put this cors configuration when serving stuff via
artisan if its even possible?
Alright found the answer at least one working for me. It would seem I was approaching the problem from the wrong direction since I concentrated on Apache instead of Laravel itself.
In order to allow Cross Origin Response in a development environment via artisan the following code should be inserted in filters.php:
<?php
...
App::before(function($request)
{
if($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
$statusCode = 204;
$headers = [
'Access-Control-Allow-Origin' => '*',
'Access-Control-Allow-Methods' => 'GET, POST, OPTIONS',
'Access-Control-Allow-Headers' => 'Origin, Content-Type, Accept, Authorization, X-Requested-With',
'Access-Control-Allow-Credentials' => 'true'
];
return Response::make(null, $statusCode, $headers);
}
});
App::after(function($request, $response)
{
$response->headers->set('Access-Control-Allow-Origin', '*');
$response->headers->set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
$response->headers->set('Access-Control-Allow-Headers', 'Origin, Content-Type, Accept, Authorization, X-Requested-With');
$response->headers->set('Access-Control-Allow-Credentials', 'true');
return $response;
});
...
Also in case it is relevant I also added 'Access-Control-Allow-Origin' => '*' to Apache configation.
So now I can run my server environment in localhost:8000 and my frontend in localhost:9000 and they can talk to each other without problem.
I faced the same issue. You can find cors configuration in config/cors.php. By default all origins allowed only for api/* routes. You can add your own routes (e.g. oauth) to it like following:
'path' => ['api/*', 'oauth/*']

Categories