Lumen Enable CSRF Token - php

I know lumen is used to session less API development still i have a situation where i need to enable CSRF token.Session every think works fine but i need to enable csrf token if i add
<input type="hidden" name="_token" value="{{ csrf_token() }}">
in form i got error
(1/1) ReflectionException Class
Laravel\Lumen\Http\Middleware\VerifyCsrfToken does not exist
In bootstrap/app.php i have uncommented following
$app->middleware([
'Illuminate\Cookie\Middleware\EncryptCookies',
'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse',
'Illuminate\Session\Middleware\StartSession',
'Illuminate\View\Middleware\ShareErrorsFromSession',
'Laravel\Lumen\Http\Middleware\VerifyCsrfToken',
]);
even i have enabled
$app->routeMiddleware([
'auth' => App\Http\Middleware\Authenticate::class,
'csrf' => 'Laravel\Lumen\Http\Middleware\VerifyCsrfToken'
]);
if i comment csrf in middleware then i get following error
Call to undefined function csrf_token() in blade
I am using laravel "laravel/lumen-framework": "5.5.*",
can any one help me how i can enable VerifyCsrfToken in lumen

Had this same issue. Posting here if someone in future.
Found out that they removed all csrf stuff from lumen since 5.2 (not exactly sure since which version). To use csrf in Lumen 5.5 or later you need to create yourself or copy VerifyCsrfToken middleware file from laravel package of that specific version (find in github) and place in lumen middleware folder and adjust the path in bootstrap/app.php accordingly.
You may need to install illuminate/cookie or other required package manually as well.
VerifyCsrfToken.php file can be found at laravel/framework/src/illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php

From the lumen documentation Validation
Form Requests
Form requests are not supported by Lumen. If you would like to use form requests, you should use the full Laravel framework.
The Lumen microframework v5.8 don't support form, so it don't have csrf

Related

Laravel Fortify and JSON based registering result in CRSF mismatch

I'm currently toying with Laravel 9.x and Fortify.
For the starter here my environnement :
Laravel 9.19
Fortify 1.14
Postgre 15
I try to achieve something I thought was possible from reading the Fortify doc, using a third-party UI (e.g.: Mobile App) to register and login user.
So, following the documentation guide I deactivated the views generation, and migrated the tables and launched my test server using php artisan serve.
Then I try using postman to post the following json to the /register route provided by Fortify.
Postman has been setup with the following headers:
Content-Type: application/json
Accept: application/json
{
"name": "test1",
"email": "test1#example.com",
"password": "MyPassw0rd!",
"password_confirmation": "MyPassw0rd!"
}
The response returned by the request was an error 419 CSRF Token mismatch, which I understand since Laravel enforce the use of CSRF token.
Therefor I tried to add the /register route to the except array inside the middleware VerifyCsrfToken and tried again and this time I got a 201 created response.
From my understanding since the /register route exists within the web guard hence the CSRF token mechanic.
Since my final goal is to use Fortify with third-party frontend, how can achieve that without putting the route inside the except array (if possible)?
Is there a parameter to change inside config/fortify.php to allow this behavior?
Thanks for reading.
After playing I found the solution inside the middleware section of config/fortify.php
Replacing
middleware => ['web'],
with
middleware => ['api'],
Allow to user the register route without having to deactivate the CSRF on the route .

laravel MethodNotAllowedHttpException when do POST on online server

I have got MethodNotAllowedHttpException when running on online server, but on local server it runs well.
The PHP version is same, the method is used POST.
The other POST methods are runs well except this one.
on blade.php
<form action="{{ route('update.product') }}" method="POST" enctype="multipart/form-data" class="form-horizontal js-form">
on routes/web.php
Route::post('/updateProduct', [
'uses' => 'AdminController#updateProducts',
'as' => 'update.product'
]);
Update:
After I changed the route into 'get'
Route::get('/updateProduct', [
'uses' => 'AdminController#updateProducts',
'as' => 'update.product'
]);
it reach the updateProducts function.
but of course there is no data to process. So, why my post method form sent the get method? and on the browser developer tools I've got POST?
but on my local server it runs well only on online server I've got this issue.
browser dev tools
Can you try using different method if you use laravel collective.
{!! Form::open(['url' => 'client/store','method'=>'post','id'=>'client-register']) !!}
and in route it must be
Route::post('client/store', 'ClientController#store')>name('client.store').
or you can write your action
action="{{URL::to('client/store')}}"
At first see if routes are define properly.
And also you can try clearing the cache using artisan command.
php artisan config:cache
Hope it helps.
This issue occurs due to a missing module extension PDO database on the server, so upload file into the application will throws error.
Installing the module extension will resolve the issue.

Laravel 419 Error - VerifyCsrfToken issue

I have multiple Laravel sites hosted on the same server. With the latest site I've created, the contact form refuses to submit without throwing a 419 error. I have set up the routing in my web.php file just like the other websites, which have live, working contact forms, and I'm generating and sending the token exactly the same way - with {{ csrf_field() }}.
I found an answer to a similar question stating that you can disable Csrf checking by adding entries to the $except array in app/Http/Middleware/VerifyCsrfToken.php. I have verified that this does indeed resolve the 419 error:
protected $except = [
'contact',
'contact*',
];
But of course I wish to keep the Csrf functionality, and I only updated the $except array for troubleshooting value.
Does anyone know what may be different about the new Laravel environment that would have this 419 behavior despite passing the generated token? I have tried updating a number of ENV settings and toggling different things, but nothing other than modifying the $except array has had any influence on the issue.
Update
Since there has been a bit of discussion so far, I figured I'd provide some additional info and code.
First, this is an ajax form, but don't jump out of your seat just yet. I have been testing the form both with and without ajax. If I want to test with ajax, I just click the button that's hooked up to the jQuery listener. If not, I change or remove the button's ID, or run $("#formName").submit(); in the console window.
The above (ajax, old-fashioned submit, and the jquery selector with .submit();) all result in the exact same response - a 419 error.
And for the sake of completeness, here's my ajax code which is working on all of the other websites I'm hosting. I define a postData array to keep it all tidy, and I added a console.log() statement directly after it to (again) confirm that token is generated just fine and is being passed correctly with the request.
var postData = {
name: $("#name").val(),
email: $("#email").val(),
message: $("#message").val(),
_token: $("input[name=_token]").val()
};
console.log(postData);
$.post("/contact", postData, function (data) {
...
Any ideas? Could there be a configuration issue with my ENV or another file?
Progress Update!
Because the other sites are working just fine, I cloned an old site and simply overwrote the files that I changed for the new website, and bam! It's working now. Doing a little bit more digging, I ran php artisan --version on the cloned version of the site versus the non-working version, and here are the results:
Working Version: Laravel Framework 5.7.3
Non-working Version: Laravel Framework 5.7.9
Perhaps this is a bug with Laravel? Or perhaps some packages on my server are out of date and need to be updated to work with the new version of Laravel?
TLDR: This post contains lots of potential issues and fixes; it is intended for those scouring for related bonus information when stuck.
I just encountered this error using Laravel Sanctum in what looks like improperly setup middleware. Sanctum uses the auth:sanctum middleware for the guard, which is some kind of extension of the auth guard of which Laravel uses as the default, but session is handled by the web middleware group.
I can't exactly verbalize some of this internal-Laravel stuff; I am more experienced with JavaScript than PHP at the moment.
In my api.php file, I had the login/register/logout routes, and in my Kernel.php file, I copied \Illuminate\Session\Middleware\StartSession::class, from the web group into the api group.
I had to do that to fix my login unit test that was throwing an error about "Session store not on request". Copying that allowed me my postJson request to work in the unit test, but sometime later, I started seeing 419 CSRF error posting from the JavaScript app (which is bad because it worked fine earlier).
I started chasing some filesystem permission red-herring in the /storage/framework/sessions folder, but the issue wasn't that (for me).
I later figured out that with Laravel Sanctum and the default AuthenticatesUsers trait, you must use the web guard for auth, and the auth:sanctum middleware for protected routes. I was trying to use the api guard for auth routes and that was central to my 419 errors with the AuthenticatesUsers trait.
If anyone gets 419 while CSRF was working or should work, I recommend doing some \Log::debug() investigations at all the key points in your system where you need these to work:
Auth::check()
Auth::user()
Auth::logout()
If you get strange behaviour with those, based on my observations, there is something wrong with your config related to sessions or something wrong with your config related to web, api guards.
The guards have bearing on the AuthManager guard which maintains state over multiple requests and over multiple unit tests.
This is the best description I found, which took over a week for me to discover:
Method Illuminate\Auth\RequestGuard::logout does not exist Laravel Passport
As a random final example, if your session is somehow generating the CSRF token using data from the web middleware group while your routes are set to use api, they may interpret the received CSRF incorrectly.
Besides that, open Chrome dev tools and goto the Applications tab, and look at the cookies. Make sure you have the XSRF-TOKEN cookie as unsecure (ie: not httpOnly).
That will allow you to have an Axios request interceptor such as this:
import Cookies from 'js-cookie';
axios.interceptors.request.use(async (request) => {
try {
const csrf = Cookies.get('XSRF-TOKEN');
request.withCredentials = true;
if (csrf) {
request.headers.common['XSRF-TOKEN'] = csrf;
}
return request;
} catch (err) {
throw new Error(`axios# Problem with request during pre-flight phase: ${err}.`);
}
});
That is how my current Laravel/Vue SPA is working successfully.
In the past, I also used this technique here:
app.blade.php (root layout file, document head)
<meta name="csrf-token" content="{{ csrf_token() }}">
bootstrap.js (or anywhere)
window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
const token = document.head.querySelector('meta[name="csrf-token"]');
if (token) {
window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}
In my opinion, most problems will stem from an incorrect value in one or more of these files:
./.env
./config/auth.php
./config/session.php
Pay close attention to stuff like SESSION_DOMAIN, SESSION_LIFETIME, and SESSION_DRIVER, and like I said, filesystem permissions.
Check your nginx access.log and/or error.log file; they might contain a hint.
just found your issue on the framework repo.
It is not a laravel issue, your installation is missing write permissions on the storage folder, thus laravel can't write session, logs, etc.
You get a 419 error because you can't write to the files, thus you can't create a sessionn, thus you can't verify the csrf token.
Quick fix: chmod -R 777 storage
Right fix: move your installation to a folder where nginx/apache/your user can actually write.
If you are using nginx/apache, move you app there and give the right permissions on the project (chown -R www-data: /path-to-project)
If you are using php artisan serve, change it's permissions to your user: chown -R $(whoami) /path-to-project
You get it, let writers write and you're good.
Probably your domain in browser address bar does not match domain key in config/session.php config file or SESSION_DOMAIN in your env file.
I had the same issue, but the problem in my case was https. The form was on http page, but the action was on https. As a result, the session is different, which is causing the csrf error.
run this command
php artisan key:generate
I used the same app name for staging and prod, being staging a subdomain of prod. After changing name of app in staging it worked
We had this issue, it turned out that our sessions table wasn't correct for the version of Laravel we were using. I'd recommend looking to see if it's being populated or remaining empty (like ours was).
If it's empty, even when you have people visiting the site, I'd say that's what the issue is.
(If you're not using a database to store your sessions, obviously I'd suggest checking wherever you are instead.)

Laravel 5.7 Email Verification Routes

On Laravel 5.7 Email verification feature added. But on my project i do not use the default route names and added a prefix for my own purpose. Now when i added following code to add the verify routes, it shows an error.
Auth::routes(['verify' => true]);
Error message shows that the verification.verify route does not exists. Where can i update this route name in my project? Or is it the only way to use this feature is to follow the default Auth Route names?
Project Source Code Is available at https://github.com/nasirkhan/laravel-starter/tree/l57
Instead of using Auth::routes(['verify' => true]); just use Auth::routes(); and manually add these routes:
Route::get('email/verify', 'Auth\VerificationController#show')->name('verification.notice');
Route::get('email/verify/{id}', 'Auth\VerificationController#verify')->name('verification.verify');
Route::get('email/resend', 'Auth\VerificationController#resend')->name('verification.resend');
Then customise as you want :)
Anyone who gets here and is looking for tompec's version for the latest Laravel, use the below. Notice the addition of /{hash}.
$this->get('email/verify', 'Auth\VerificationController#show')->name('verification.notice');
$this->get('email/verify/{id}/{hash}', 'Auth\VerificationController#verify')->name('verification.verify');
$this->post('email/resend', 'Auth\VerificationController#resend')->name('verification.resend');
When you want to change the route throught which the verification process will be done you must change all the way the verification process work.
Email verification notification process
During the registration process an event Illuminate\Auth\Events\Registered is emit. Laravel come whith a listener Illuminate\Auth\Listeners\SendEmailVerificationNotification which is already registered in the App\Providers\EventServiceProvider.
After implementing the MustVerifyEmail interface when the Registered event is emit the SendEmailVerificationNotification listener will check if the App\User have already use the Illuminate\Contracts\Auth\MustVerifyEmail trait by checking if the user create is an instance of MustVerifyEmail if that is the case it will call the sendEmailVerificationNotification method on the user which get the implementation of this method when it use the Illuminate\Auth\MustVerify trait.
Customization of the verification route
To change the behavior of the verification process you can customize the sendEmailVerificationNotification to emit a custom event which can have a custom listener in which you will perform all the verification stuff and notify the user by email in which you will send the custom route through which the verification process will be done
In my case, I had the same issue and I was receiving the message
InvalidArgumentException
Attribute [auth] does not exist.
at vendor/laravel/framework/src/Illuminate/Routing/RouteRegistrar.php:92
I've solved it updating my composer executable file and laravel local files.
composer global self-update
composer update
It seems that my composer executable was using and old version of laravel installer.

PHP laravel 4.2 API Routing URL with postman

I'm new to laravel4.2 trying to create a RESTFUL API, but getting error when I'm trying to hit URL{localhost/TPM/public/api/books} in postman.
what would be the URL for this??
Controller:
Router:
Try with return Response::json(['result' => true]); in your index method.
In addition, you can check the logs file for clues of what's going on in storage/logs/laravel.log.
I think in Laravel 4.2 you needed to perform a composer dump-autoload if created new classes but not sure.

Categories