Laravel Sanctum auth route is showing unautheticaed only in production - php

Hi I have recently set up my laravel 8 app with sanctum as api token provider. my login works fine and token is received. this token I am using to get the user.. which works fine for me in localhost..
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
but when I deployed the same application to production.. get user is always resulting to "Unauthenticated". I am not using SPA, and only wish to use API tokens my production API path is like this https://xxx.app/api/user I have already set this to my .env file SESSION_DOMAIN=https//xxx.app SANCTUM_STATEFUL_DOMAINS=https//xxx.app
the SANCTUM_STATEFUL_DOMAINS
also i try to put this in .htaccess
RewriteCond %{HTTP:Authorization} ^(.+)$
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
i have 2 files htaccess one outside public folder to redirect all request to public index
another one inside public folder to redirect all requests to index.php
i want to get auth user

Related

Getting 403 Forbidden error message when trying to access a cusotm route

I'm working with Laravel 5.8 to develop my project and in this project, I have added this route:
Route::namespace('StaticPages')->prefix('tavana')->group(function () {
Route::get('/', 'TavanaStaticController#index')->name('tavanaMainFrontend');
...
});
So when I goto the url sitename.com/tavana/, it should be retrieving data from TavanaStaticController Controller.
But now the problem I'm facing is that, it shows 403 Forbidden:
Forbidden You don't have permission to access this resource.
This is strange, because it used to work fine!
So what's going wrong here? How can I solve this issue?
Run the following command and see if a middleware is specified for this path or not
php artisan route:list
In the middleware column you will see the items that cause you to make a 403 error.
Check out that middleware
It was basically because of these codes written at .htaccess file in public directory:
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
So when I go to a url like /example on my website, it searches in public directory and if not any folder name exists with the same name, then it will calls the Controller and its methods.

Laravel, Sending API routes back to server

So I've got a project which is React on the FE and Laravel BE. 99% of all routes are handled through React router, which is fine in the wep.php i've got the following where sends are requests to be handled by React
//routes/web.php
Route::get('/{path?}', [
'uses' => 'App\Http\Controllers\ReactController#show',
'as' => 'react',
'where' => ['path' => '.*'],
]);
The problem comes as we're been asked to implement a wordpress integration which sits inside a sub folder /blogadmin
The problem I'm having is that when I try to hit an endpoint on the wordpress api (using wither graphql or the rest api) e.g. www.mydomain.com/blogadmin/graphql or www.mydomain.com/blogadmin/wp-json/wp/v2 the routing is passed to laravel and then back to React.
How can I make the word press endpoints accessible?
I've tried adding Route::get('/blogadmin/graphql'); to web.php as I thought that intercept the request, but no luck!
Ok, I was looking at this the wrong way, it's a simple entry in .htaccess
RewriteCond %{REQUEST_URI} !^/blogadmin
directly before
RewriteRule ^ index.php [L]
fixed the problem

Laravel sanctum unauthenticated

I am using Laravel sanctum in my project with angular as frontend. Getting unauthenticated from the second api request. Please let me know where am I going wrong
Frontend-> 127.0.0.1:4200
Backend-> localhost:8888
.env config
SESSION_DOMAIN=localhost
SANCTUM_STATEFUL_DOMAINS=127.0.0.1
Added middleware auth:sanctum to the routes group in api.php
Ref: https://prnt.sc/rm9ejy
For anyone having an Unauthenticated error, please ensure you follow these steps.
Send a GET request to /sanctum/csrf-cookie
Send a post request to web route /login to get authenticated
After this step, you will be successfully authenticated by auth:sanctum middleware in the WEB route or any resource route that needs CRSF token present.
[Why did this work]
Sending a GET request(empty request) to /sanctum/csrf-cookie enables laravel to send the fresh set cookies command to your browser to set a fresh CRSF token which can be found in your cookies. Axios and most library send this fresh token as part of headers X-CSRF-TOKEN by default, for regular ajax request, please include them explicitly in your headers or in form _token, else your SPA will still hit the 419(token expired) error
Other things to be aware of:
Ensure your SESSION_DOMAIN is set to localhost
SANCTUM_STATEFUL_DOMAIN is set to your sub domain/SPA with the port e.g localhost:8000
For the original question please ensure you maintain same domain. I mean use localhost for both. And set SANCTUM_STATEFUL_DOMAIN = localhost:4200
Edited
Also set SESSION_DRIVER
Add your domains, for example
my API is running on localhost:8000 my client is running on localhost:3000 so my env setting looks like below
SANCTUM_STATEFUL_DOMAINS=localhost:8000,localhost:3000
also, add your session domain
SESSION_DOMAIN=localhost
Have you checked your Kernel.php? app/Http/Kernel.php
Make sure you uncomment \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class, coz by default it is being commented
'api' => [
\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
Two days of pain and despair to arrive at this conclusion: the Bearer token was not attached to the request, and that was because of my .htaccess configuration.
If you, like me, are not able to authenticate via API token, try to add this line on your .htaccess file in the public directory in your Laravel project:
RewriteRule ^ - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
Right after RewriteEngine On directive.
CREDITS: Laravel not detecting auth token sent in the header and JWT package
From the screenshot you shared I see your domain is localhost and not 127.0.01, just do:
SANCTUM_STATEFUL_DOMAINS=localhost
For anyone using Laravel Homestead, use your actual domain.
SANCTUM_STATEFUL_DOMAINS=homestead.test
Which version are you running? Since V2.4.0 you need to specify the port:
SANCTUM_STATEFUL_DOMAINS=localhost:4200
See this issue for more info.
The sanctum stateful domains require the port number as well.
e.g. SANCTUM_STATEFUL_DOMAINS=127.0.0.1:4200
Although in your case your screenshot shows it should be SANCTUM_STATEFUL_DOMAINS=127.0.0.1:4201
Late in the game but just to help those that keep looking for this solution, most of the answers here have some truth, just have to put them together to make it work:
ENV file: SESSION_DOMAIN=localhost (or whatever your domains is)
in config->sanctum.php->stateful (if not already there): Sanctum::currentApplicationUrlWithPort()
in app/Http/Kernel.php API add as very first (this is important) : \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
in app/http/kernel API remove if there: \Illuminate\Session\Middleware\StartSession::class,
add to your api routes middleware: auth:sanctum
Also worth checking the guard settings under config->sanctum.php
that should do.
I had the same solution as Marco, adding the rewrite rule to my htaccess in public fixed it.
RewriteRule ^ - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
FYI I am hosting this on Auzre Web App Service (linux), if anyone else is doing that.
check if you had changed your guard in past. goto config/auth.php check if your provider model is same as your user model (or the model you using) for authentication.
in my case i was using different guard and provider.
In case you have problems when going into production and/or have more than one subdomains and also use https don't forget that the port is 443 instead of the usual 80.
E.g.:
SANCTUM_STATEFUL_DOMAINS=*.example.com:443
SESSION_DOMAIN=.example.com
Lost days trying to figure out why the laravel, the spa or the android app were taking turns to fail, but never working all at the same time, until found that solution.
This worked for me. The solution is adding this to .htaccess of root folder (not only inside the public folder)
# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

Laravel + passport: Facing issue 401 Unauthorised

I have created a Laravel Application and included passport for authentication. The application is working fine on my local system.
But when I have deployed the application on the shared hosting platform I am facing issue where I am getting error 401 Unauthorised on the request I am passing to the server.
Though, the login API is working fine and generating access token. I am facing difficulty to find out the reason for it.
Could anyone help me out to resolve this issue?
Attaching image the way I am sending the request:
Did you send access_token in your headers like this:
$.ajaxSetup({
headers: {
'Authorization': "Bearer your_access_token",
}
});
Add below code in .htaccess file
RewriteEngine On
RewriteCond %{HTTP:Authorization} ^(.+)$
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

laravel 5 authentication not working

I have the following problem. I'm developing a website using php and laravel 5.0.33. I have a development machine and a web server.
Now, I'm intercepting the register process by overriding the AuthenticatesAndRegistersUsers postRegister method, but with no luck because the interception is not performed on the server, on my local environment all works as expected.
I have also putted a die(); on the postRegister method of my AuthController, the one that overrides the defined on the mentioned trait and that line is never reached.
Original Trait method on \Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers :
public function postRegister(Request $request) {
$validator = $this->registrar->validator($request->all());
if ($validator->fails()) {
$this->throwValidationException(
$request, $validator
);
}
$this->auth->login($this->registrar->create($request->all()));
return redirect($this->redirectPath());
}
My overrided method inside AuthController on \Project\Http\Controllers\Auth\AuthController :
use AuthenticatesAndRegistersUsers;
//Override of the register process
public function postRegister(\Illuminate\Http\Request $request) {
die ('aqui');
}
So, what is preventing the code from entering my overrode method?
In both, my local dev machine and the server, the php versions are the same.
Edit: Bad news the same behavior happens if I try to log in a user on the website, the login is not working as the register. The request never gets to the controller. This has cost me a whole day....:(. On the login I also overrode a method.
So, the error was due to a misconfiguration on the virtual host done by the hosting providers in which all requests urls get a trailing slash, but if a POST request is done and the trailing slash is added then the consequent redirection transforms the POST request into a GET one. After two days of explaining this to the hosting providers, I got the access to modify the virtual host configuration and I added a rule to avoid redirecting POST requests.
This was the redirection before the fix:
# Enforce trailing slash policy
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*[^/])$ /es/$1/ [L,R=301]
And the redirection after the fix:
# Enforce trailing slash policy
RewriteCond %{REQUEST_METHOD} !=POST
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*[^/])$ /es/$1/ [L,R=301]
Thanks to all for your interest and responses.

Categories