404 Not Found on sanctum/csrf-cookie path - laravel

So I've been building a projet based on laravel. I'm building on a SPA foundation with sanctum as my authorization package. It works perfectly. Then I deploy the project to the server and everytime I try to login there is a 404 error on /sanctum/csrf-cookie.
How could this happen? Is it because the SanctumServiceProvider not working.

The problem is when you define sanctum prefix, the route become something else like this:
you can check your routes with : php artisan route:list
as you can see the /sanctum/ is removed and when you check the route /sanctum/csrf-cookie it will not be and throws 404 error. So you have two options:
add this prefix: 'prefix' => 'api/v1/sanctum'
or
change GET call to api/csrf-cookie

You need to check if you're setting correct axios defaults for your /sanctum/csrf-cookie api call.
You can set it as follows
axios.defaults.withCredentials = true;
axios.defaults.baseURL = "http://localhost"; //Before sending get request
axios.get("/sanctum/csrf-cookie").then(async () => {
//Logic to handle login
});
If defaults are not set properly url becomes http::localhost::8080/sanctum/crf-cookie which is where frontend is serving but instead it has to be http::localhost/sanctum/csrf-cookie
Note: localhost example is just for explanation. For production server make sure your url is correct and api call is on backend.

I solved this issue by adding:
AllowOverride All
to the apache directory config

add in last line inside config/sanctum.php
'routes' => false,

Add in config/cors.php
'paths' => ['*']

Related

Getting GET error while sending POST request to the POST route in Laravel API

Locally project runs fine. On the server getting this error while sending POST request to the POST route in Laravel 9 API.
"message": "The GET method is not supported for this route. Supported methods: POST."
My route from the api.php routes file:
Route::post('/userdata/create', [UserDataController::class, 'createAccount']);
My route from the routes list (from php artisan route:list):
POST api/v1/userdata/create .......... Api\V1\UserDataController#createAccount
Tried:
php artisan cache:clear
php artisan route:cache
php artisan route:clear
Didn't fixed it yet.
It happens cause you have forced your domain to HTTPS redirect and you are trying to use it as HTTP.
Your domain settings redirect your request to HTTPS but not to POST method.
If you look for postman logs/console you will find redirection of HTTP POST request to HTTPS GET request
Hence Error response by your server of
The solution to that problem was actually very simple:
I needed to send POST request to "https" url, and i was sending it to "http" url.
Still strange that server was complaining that GET method is used...
This problem happened to me recently where I was using .com instead of .net
that happen because laravel cannot return the error.
SOLUTION 1 :
you can use this inside your API post function :
try{
// example we have name field
$request->validate([
'name' => ['required','string','max:255']
]);
User::create([
'name' => $request->name
]);
return 'registered';
}catch(Exception $error){
// your error from validation will appear here
// dd($error->validator->messages());
}
SOLUTION 2 :
as alternative :
I found another method here at this link

Laravel Sanctum SPA Auth - Unauthenticated After Successfully Login

I have an application with Laravel and Vue.js for the separate folder which one is for the backend and another is the frontend and I have successfully configured all following the Laravel sanctum documentation and also protecting the route API and I am able to successfully log in and register but after successfully Login it's showing me "Unauthenticated " when I try to fetch the authenticated user. I am using localhost as a default. can anyone give me some suggestions
.env file I have also set it
SESSION_DRIVER=cookie
SESSION_DOMAIN=localhost
SANCTUM_STATEFUL_DOMAINS=localhost:8000
Thanks
Unfortunately, I have found the solution
#localhost
SESSION_DRIVER=cookie
SANCTUM_STATEFUL_DOMAINS=localhost:8080,127.0.0.1:8080,localhost:3000,127.0.0.1:3000
SESSION_DOMAIN=localhost
localhost:8080 for frontend server the port might be changing sometimes like localhost:8081 localhost:3000 so make sure you put the correct URL
#Live Server
SANCTUM_STATEFUL_DOMAINS=*.yourdomain.com
SESSION_DOMAIN=.yourdomain.com
I have also figure out sometimes I was right but the Laravel cache gives me the wrong result so you have to clean the Laravel cache and also browser cache. you can follow the below code to make a route function in web.php
Route::get('/clear', function() {
Artisan::call('cache:clear');
Artisan::call('config:clear');
Artisan::call('config:cache');
Artisan::call('view:clear');
return "Cleared!";
});
Hope it will works
Thanks

Why am I getting 404 error on my livewire.js connection?

I am using Laravel 8. "wire:model" also not working because of this.
you need to setup livewire base url
in config/livewire.php
'asset_url' => env('APP_URL', 'http://localhost'),,
then in .env
APP_URL=your_app_url
in config/livewire.php
'asset_url' => url('/'),
You need to setup the livewire app url in config/livewire.php.
'app_url' => url('/'),
Just the following code to your admin or control panel routes:
use Livewire\Controllers\HttpConnectionHandler;
Route::post('livewire/message/{name}', [HttpConnectionHandler::class, '__invoke']);
And remember to override the url using this one linear:
<script>
window.livewire_app_url = '{{route('admin.index')}}';
</script>
More detailed answer could be found here
Laravel - Livewire, how to customize the global message URL?

Laravel Passport Password Reset API route

I'm all set up with Passport in 5.5 and have the auto generated Auth\ForgotPasswordController and Auth\ResetPasswordController controllers.
However whereas /oauth/token was provided magically for me, there don't appear to be such routes for password reset when using the API.
What should my API routes look like?
Currently I've experimented with
Route::group(['prefix' => 'password'], function () {
Route::post('/email', 'Auth\ForgotPasswordController#sendResetLinkEmail');
Route::post('/reset', 'Auth\ResetPasswordController#reset');
});
but I found these in the vendor files when looking at the traits and aren't sure if this is the correct way.
The /password/email route also fails with "message": "Route [password.reset] not defined."
since you don't see any route other then 2 custom, therefore i am assumin you havn't run artisan auth command. First run that. it will add lot of routes in ur project.
Then set api driver to passport.

Laravel & PHPUnit: Getting 500 when unit testing "Passport" restricted route

I have a Laravel 5.3 app.
Inside my api.php file, there's a route for posting an answer within a poll.
Route::group(['middleware' => 'auth:api'], function () {
Route::post('/poll/answer', 'API\PollsController#createAnswer');
});
The route is part of a group, restricted by the auth:api middleware, using Laravel's Passport engine.
When calling this route from Postman or any other tool to test APIs, I get 401 which is ok because I'm not attaching the token.
But when unit testing this call using PHPUnit, it returns 500. I have no idea why.
$this->postJson('api/poll/answer');
I'm probably missing a configuration or setup instruction.
Any ideas?
The 500 error was occurring because I forgot to add an app key to the .env.testing file.
It got solved after adding that.

Resources