Laravel Sanctum Angular Authentication 419 error code - php

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

Related

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 Sanctum not authenticating when both api and SPA are on subdomains

I have been trying to get subdomains working with Laravel Sanctum for about 2 hours tonight, I had it working when my SPA was at app.domain.com and my api was at domain.com but now I need to move the api to be hosted at api.domain.com but for whatever reason when both the session_domain and the sateful_domain are subdomains things get all wacky. Wondering if anyone has had similar issues. Can't find anything helpful online either.
.env file
SESSION_DRIVER=cookie
SESSION_LIFETIME=120
SESSION_SECURE_COOKIE=true
SESSION_DOMAIN=.domain.com
SANCTUM_STATEFUL_DOMAINS=app.domain.com
config/cors.php
'paths' => ['api/*', 'login', 'logout', 'register', 'sanctum/csrf-cookie'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => true,
Kernel.php
'api' => [
\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class
],
CSRF protection is working fine, and I am able to "login" but any request after the successful login 401's and every time I login again another cookie is added to the browser.
I have followed everything on the laravel docs, would love some help here if someone has the time / has ran into this before
All of my api routes are guarded with Route::group(['middleware' => 'auth:sanctum']
I have even tried the findings from this post and still no dice.
Laravel Sanctum auth:sanctum middleware with Angular SPA unauthenticated response

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.

AWS Amazon Server : cURL error could not resolve host

I've been using a fanless ubuntu server for a couple of months and been transferred my Laravel API Passport to different servers like Ubuntu and for development Windows.
The current version of my api is working fine on these servers. Not until when I transferred the laravel project to my AWS Amazon server and getting the error like this
{
"message": "cURL error 6: Could not resolve host: api-a.mydomain.comoauth (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)",
"exception": "GuzzleHttp\\Exception\\ConnectException",
"file": "/var/www/html/api_tk_a/vendor/guzzlehttp/guzzle/src/Handler/CurlFactory.php",
"line": 185,
"trace": [
{
....some line of multiple errors
}
]
}
I tried to add some line of code to my etc/hosts file
like this
52.***.***.205 api-a.mydomain.com
52.***.***.205 api-b.mydomain.com
or
127.0.0.1 api-a.mydomain.com
127.0.0.1 api-b.mydomain.com
tried also my inet addr:171.*.**.** to put on my hosts file still getting the same error
I have 2 different api that's why there's a and b
But nothing of these works.
Can anyone point out the reason why I'm getting this error.
Some thread says this has nothing to do with the Guzzle but clearly states to the IP and DNS. But I can't find a good way to figure this out.
UPDATE
My .env file has something like this
APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:1AEVUl5JHMzLkhxU7MDlDHtfZ6KB9UybjzUxLaYp9vg=
APP_DEBUG=true
APP_URL=http://localhost
I tried to put the APP_URL as https://api-a.mydomain.com still not working..
API CODE This code is working fine
$http = new Client;
$response = $http->post(url('oauth/token'), [
'form_params' => [
'grant_type' => 'password',
'client_id' => '2',
'client_secret' => '8mEsN0RZkljKZlbiJFfnNKahcbcOVkoQVG7C2Xwl',
'username' => $user->email,
'password' => $request->password,
'scope' => '',
],
]);
This is my routes/api.php
use Illuminate\Http\Request;
Route::post('/login','Auth\Api\AuthController#login');
EC2 Ping
For ping to work in EC2 instance, you have to open ICMP port in Security Group for your IP. Also for curl, verify have you opened port 8080/80 for your instance.
I found a solution:
I used $http->post('https://api-a.mydomain.com' . '/oauth/token', [
Laravel passport trying to get oauth/token. Guzzle keeps hanging, also on other Guzzle calls

Categories