Laravel Sanctum unauthenticated using postman - laravel

I follow the Laravel official document step by step.
When I send a request to {{host}}/api/login, I can receive the response that includes the token. Everything is correct.
But when I try to send a request to {{host}}/api/user, it is always unauthenticated.
I checked my code several times, I cannot fix it.
In my .env file, I set as following, my backend host is http://laravel_8_api.test
SESSION_DOMAIN=.laravel_8_api.test
SANCTUM_STATEFUL_DOMAINS=.laravel_8_api.test
How can I make it work? Please help me.
The code is in this link https://github.com/ramseyjiang/laravel_8_api

Try this if you haven't
The reason this isn't working is that Sanctum is denying the authenticated request based on the referrer.
Add Referer to the request header in postman.

//api.php
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
middleware should be auth:sanctum instead of auth:api

In the official document, it forgets to modify the config/auth.php
'api' => [
'driver' => 'sanctum',
'provider' => 'users',
'hash' => false,
],
After that, it will fix this issue.
Don't need to modify code in the code in the api.php
I mean it doesn't need to change auth:sanctum to the auth:api, if change it, it will make another issue as the link Laravel Sanctum : column not found: 1054 Unknown column 'api_token' in 'where clause'

Try this solution, may it will help you.(It helped me)
first you check is that your bearer token which you sending in header is really reaching to your app server?
Lets check it:
put this code in your route/api.php file
print_r($_REQUEST);
print_r($_SERVER);
exit;
now lets send postman request,
in response you will get a line like this
"[REDIRECT_HTTP_AUTHORIZATION] => Bearer 6|4rxthBID7kiSleFglD30aphZu3poiDYJjWMJgZZc"
if this line is missing then its mean your .htaccess file is not allowing to pass token to server.
So the solution is very easy, just add this line to your .htaccess file
#Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

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

404 Not Found on sanctum/csrf-cookie path

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' => ['*']

laravel 6 session restart through each request

I'm working with Laravel 6, and my session driver is file. I've faced a 419|page expired when I submit a form with post action and after tracing the codes I found out the session will restart after submission. Everything is good on local but on the server I've got this issue.
I tried with a raw Laravel project and it worked!
I've already checked directory permission, config/session.php,.env file.
.env
SESSION_DRIVER=file
SESSION_LIFETIME=120
config/session.php
'driver' => env('SESSION_DRIVER', 'file'),
'lifetime' => env('SESSION_LIFETIME', 120),
'expire_on_close' => false
Tnx for responding.
the problem is not because of CSRF token, it's session's fault. evry time a new session and new token will be started so the token thet I send from input will be checked with another token !!!
If your form is in a blade, after starting the <form>, add a csrf field by putting #csrf.
If you're sending the POST request from somewhere else (i.e. from some other domain/subdomain that is not project domain) you may want to disable CSRF check by adding it in VerifyCsrfToken.php (\app\Http\Middleware\VerifyCsrfToken.php) like this:
class VerifyCsrfToken extends BaseVerifier
{
protected $except = [
// Place your URIs here
];
}

Laravel - GET request download logout automaticlly

i have a download file link like this:
Download file
ROUTES
Route::group(['middleware' => ['web','auth','Admin','active'], 'prefix' => 'admin'], function(){
// USERS
Route::resource('user','UserController');
Route::post('user/permissions/update','UserController#update_permission')->name('update_user_permissions');
// MODULI
Route::resource('module','ModuleController');
// MODULISITICA
Route::resource('modulistica','ModulisticaController');
Route::post('modulistica_cliente','ModulisticaController#update_client_module')->name('modulistica_post_cliente');
Route::post('modulistica_prodotto','ModulisticaController#update_product_module')->name('modulistica_post_prodotto');
Route::get('modulistica/download/cliente/{file}','ModulisticaController#download_cliente')->name('modulistica_download_cliente');
Route::get('modulistica/download/{file}','ModulisticaController#download_module')->name('modulistica_download_module');
Route::get('modulistica/download/prodotto/{file}','ModulisticaController#download_prodotto')->name('modulistica_download_prodotto');
// UTILITY
Route::post('utility/become/client','UtilityController#become_client')->name('utility_become_client');
Route::resource('loan','LoanController');
Route::get('area_download/document/{file}', function ($file){
$path_file = storage_path().'/app/public/documents/'.$file;
return response()->download($path_file, $file);
})->name('download_document');
});
ERROR
Arrival at the "https://mysite.it/admin/loan" view without problems. When I click on the GET link it redirects me to the LOGIN, but being my user logged in by login redirects me to "https://mysite.it/home".
I did some tests getting the following information:
Request does not arrive at route "area_download / document / {file}"
The request does not arrive at the 'Admin', 'active' middlewares.
So my conclusions are that the problem is in the middleware "Web" or "Auth" but I can not understand why. Place the entire group of routes, if it can be useful. If you need more on the routes, I can attach screenshots!
I would appreciate your help thank you!
If you just allow downloading a file without any authentication then,
You can try this :
Blade File
Download file
From this user can directly download the file. Just need to add file path in href and download attribute.
or else remove the middleware AUTH if you don't want to Authenticate the user.
And you want to authenticate the user then need route:list and middleware details.
I found the solution! the problem was that my get request was made this way.
https://mysite.it/admin/area_download/document/example.pdf
the final PDF extension creates system error. Avoiding the final extension such as:
https://mysite.it/admin/area_download/document/example.pdf/go
Problem solved!

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 🍻

Resources