Laravel 5.3 - TokenMismatchException in VerifyCsrfToken.php line 68: - laravel-5.3

When I log in to my app, and immediately go back when I enter it, and then try to log out, I get the error from the title, how can I fix that?

I was facing same issue with laravel 5.4 .. and then following command works for me :)
chmod 777 storage/framework/sessions/
before this, it was chmod 775 storage/framework/sessions/ ... hence I was facing the issue...
Happy coding

I solved this problem by editing the file config->session.php
'domain' => env('SESSION_DOMAIN', null),
and removing SESSION_DOMAIN from the file (.env)
and finally composer dumpautoload

From Laravel 5.3 docs
The Auth::routes method now registers a POST route for /logout instead of a GET route. This prevents other web applications from logging your users out of your application. To upgrade, you should either convert your logout requests to use the POST verb or register your own GET route for the /logout URI:
Option One:
Route::get('/logout', 'Auth\LoginController#logout');
For more about upgrade please have a look at this https://laravel.com/docs/5.3/upgrade
Option 2
//Insert this on your head section
<!-- CSRF Token -->
<meta name="csrf-token" content="{{ csrf_token() }}">
<!-- Scripts -->
<script>
window.Laravel = <?php echo json_encode([
'csrfToken' => csrf_token(),
]); ?>
</script>
Where you want you logout
<ul class="dropdown-menu" role="menu">
<li>
<a href="{{ url('/logout') }}" onclick="event.preventDefault();
document.getElementById('logout-form').submit();"> Logout
</a>
<form id="logout-form" action="{{ url('/logout') }}" method="POST" style="display: none;">
{{ csrf_field() }}
</form>
</li>
</ul>
Cheers

I faced this issue because I set 'secure' => env('SESSION_SECURE_COOKIE', false), to true for my localhost. The value is in the project-folder/config/session.php file. Since my localhost wasn't https that's why I was facing the issue. After making it false for my localhost the issue disappeared.

I have added SESSION_DOMAIN=localhost in my .env file when my APP_URL is APP_URL=http://localhost. It works for me I use laravel 5.3

Actually i have the same issue in Laravel 5.4, when I upload a file using a form, I sent the token and the file uploads correctly. The issue appears when I upload a file that exceeds the max filesize upload. So, just add an exception in the VerifyCsrfToken.php for the route and the message disapears, but the file doesn't get upload.
use Closure;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;
class VerifyCsrfToken extends BaseVerifier {
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
protected $except = [
'anexoSesion',
];
public function handle($request, Closure $next)
{
return parent::handle($request, $next);
}
}

I had the same problem.
I run Laravel / PHP on a Windows machine with IIS. If you do as well, please make sure, the user IUSR have modify rights on the project directories.
After permitting the user, the error was gone.

This issue will generally occur due to permissions. As Manish noted you can chmod 777 on your sessions folder, however, I would not recommend this ever. First check if you have the same issue with the app using artisan serve (as opposed to serving your app via Nginx or Apache). If you don't then it is a permissions issue and you can change the ownership of the folder accordingly. Most likely it is the www-data user that needs permissions to write to the folder, however, you will want to check your environment to make sure as the user will differ in some cases.

To solve this add those two lines in the route file (e.g web.php)
Route::get('/', 'HomeController#index');// so when you logged out it go back
Route::get('/home', 'HomeController#index');
This solved the problem for me. Hope that help.

Illuminate\Foundation\Http\Middleware\VerifyCsrfToken.php
use Closure; // import
protected $except = [
//
];
public function handle($request, Closure $next)
{
$response = $next($request);
if (last(explode('\\',get_class($response))) != 'RedirectResponse') {
$response->header('P3P', 'CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"');
}
return $response;
}
or
for all url
protected $except = [
'*'
];
or
If there is no use
Illuminate\Foundation\Http\Kernel.php
// \App\Http\Middleware\VerifyCsrfToken::class
this line add comment

Out of the box, Laravel comes with web and api middleware groups that contains common middleware you may want to apply to your web UI and API routes
If you check your app/Providers/RouteServiceProvider.php, you will find that by default, a web middleware group is applied to all your routes in routes/web.php.
protected function mapWebRoutes()
{
Route::group([
'middleware' => 'web',
'namespace' => $this->namespace,
], function ($router) {
require base_path('routes/web.php');
});
}
Now, if you go check your app/Http/Kernel.php and take a look at the $middlewareGroups property, you will find a new EncryptCookies middleware. You can read about it, but if you remove this middleware from the web middleware group, your app might not give the TokenMismatchException which you are getting currently.

I am also facing this problem when using laravel5.4 for rest API. Just add the route name to the app/Http/Middleware/VerifyCsrfToken.php file.
protected $except = [
'test/login',
];
After adding the line, then I run the API, it executes successfully.

I faced this kind of problem in version 5.3.29
The following method worked for me.
Just change the following line in your .env file.
APP_KEY=base64:aBCdeFghI+jKLMnOPqRSTuvw1xYzAbCDeFgHiJKL57+4= (example key)
remove the base64: part, and make it like following
APP_KEY=aBCdeFghI+jKLMnOPqRSTuvw1xYzAbCDeFgHiJKL57+4=

go to middleware -> verifycsrftoken.php -> add the urls in the array specified.

Related

Output page is parsed as XML in a browser

At first, I saw a topic Symfony Twig and xml - Document is empty error and my case is similar, but provided answers there, did not help me.
So my problem is: sometimes I got parsing error in a browser.
In chrome it is:
This page contains the following errors:
error on line 38 at column 21: Opening and ending tag mismatch: link line 19 and head
Below is a rendering of the page up to the first error.
But on firefox things get a little bit more accurate? (I got non-english version so here is my translation of this error):
Error parsing XML: wrong tag. Expected </link>
So my guess is, Symfony somehow provide XML document to the browser, instead of HTML.
But looking at the source code, or even at Inspector, there is nothing that would indicate XML. I got <!DOCTYPE html> tag at start, and proper tags.
When this error occur document in Inspector in Chrome is parsed, like <LINK> tags should have end tags (</LINK>) and everything under this tag is considered as be inside this <LINK> tag. But message in Firefox gave me answer: XML document, so <LINK> tag is treated like tag with closure.
But what is more important, this happening only sometimes, not always. For most of the time I got good looking website, with everything working, all tags parsed, all assets loaded, Javascripts working well.
Why this could happen that sometimes, Symfony put XML file instead of HTML to a browser?
I have an idea, that this could be because of HTTP-CACHE I have inserted in my app in the controller action. Maybe I configured something in a wrong way.
Or maybe there is something else wrong in here? Maybe in other YAML configuration file?
public function index()
{
$categories = [ ... ];
$articlesByCategory = [ ... ]; // is readed correctly - checked
return CacheService::buildCachedResponse($this->render('pages/home.html.twig', [
'categories' => $categories,
'articles' => $articlesByCategory,
...
]), self::CACHE_TIME);
}
class CacheService
{
public static function buildCachedResponse(Response $response, int $expirationSeconds)
{
$response->setPublic();
$response->setMaxAge($expirationSeconds);
$response->headers->addCacheControlDirective('must-revalidate', true);
return $response;
}
}
class CacheKernel extends HttpCache
{
protected function getOptions(): array
{
return [
'default_ttl' => HttpCacheTimesPerController::DEFAULT,
];
}
}
Kernel switched to "CacheKernel" in "public/index.php", as showed in Symfony documentation.
INFO: currently app is running on symfony 5.x, and php 7.4.

How can I make a dynamic route start with an # symbol? Like "mywebsite.com/#username"

My goal is to have two kinds of dynamic routes on the same path. I want:
mywebsite.com/#username to send people to /pages/[username].tsx
mywebsite.com/page-slug to send people to /pages/[pageSlug].tsx
I tried creating two files:
/pages/[pageSlug].tsx
/pages/[...username].tsx
So that [pageSlug].tsx would have priority, and then everything else would go to [...username].tsx, where I would extract the username from the path and render the page.
It works great locally, but on vercel mywebsite.com/#username pages return 404 error.
I have also tried following this advice about doing this with url rewrites, but it doesn't seem to work.
I have created two files:
/pages/[pageSlug].tsx
/pages/user/[username].tsx
Set up the rewrites in next.config.js:
module.exports = {
reactStrictMode: true,
async rewrites() {
return [
{
source: '/:username(#[a-zA-Z0-9]+)/:id*',
destination: "/user/:username/:id*",
}
]
}
}
And set up the links to the user profiles like so:
<Link href="/user/[username]" as={`#${post.author.username}`}>
{post.author.username}
</Link>
Just loading the http://localhost:3080/#lumen works, but when I click on a link I'm getting:
Error: The provided as value (/#lumen) is incompatible with the href value (/user/[username]). Read more: https://nextjs.org/docs/messages/incompatible-href-as
How can I make this work with the rewrites (or in any other way)? Any advice?

Build error when fetching page data: Cannot read property 'b' of undefined

I am getting a typeerror when trying to build my next js project, 'cannot read property b of undefined' (nowhere in the app do I try to access a property 'b' so it doesnt say much).
It seems to go away when I comment out all children in inside of the page component but not one specific child causing the issue e.g:
// error
function MyPage({dataFromGetStaticProps}:dataType)){
return (
<Div>
<Comp1 />
<Comp2 />
<Comp3 />
</Div>
)
}
// error when individually commenting out a child
function MyPage({dataFromGetStaticProps}:dataType)){
return (
<Div>
<Comp2 />
<Comp3 />
</Div>
)
}
// works
function MyPage({dataFromGetStaticProps}:dataType)){
return (
<Div>
</Div>
)
}
I have tried running --debug with the build but it shoes nothing and the app runs fine when running next dev.
Does anyone know what could be causing this?
I have:
Checked my imports
Checked the data being received by the function is valid and of expected type
Checked there is no errors on on the api where the data is coming from i.e that my production server serving data to the app is working fine (even switched it to the local one but still no luck)
Running yarn build with the NODE_ENV = development causes all of the errors to disappear
This turned out to be a circular dependency, You can add this plugin to the next config file here and see if you have any
webpack: (config) => {
config.plugins.push(
new CircularDependencyPlugin({
allowAsyncCycles: false,
cwd: process.cwd(),
})
);
return config;
},

Undefined index stripeToken

I have a stripe checkout error in my symfony project. Here is my view that uses checkout by default :
<form action="" method="POST">
<script
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="pk_test_C9N5xzeBHyGplmZwpsbyciS6"
data-amount="9999"
data-name="Demo Site"
data-description="Widget"
data-image="https://stripe.com/img/documentation/checkout/marketplace.png"
data-locale="auto"
data-zip-code="true"
data-currency="eur">
</script>
</form>
The method of my controller:
public function paiementAction(Request $request)
{
\Stripe\Stripe::setApiKey("sk_test_5W9Z1CdBKN2G46sTa2O5KI3T");
$token = $_POST['stripeToken'];
try {
$charge = \Stripe\Charge::create(array(
"amount" => 1000, // Amount in cents
"currency" => "eur",
"source" => $token,
"description" => "Example charge"
));
return $this->redirectToRoute("chk38_platform_confirmation");
} catch (\Stripe\Error\Card $e) {
// The card has been declined
return $this->redirectToRoute("chk38_platform_commande");
}
}`
Error Symfony
Thank you for your help
This issue of $_POST['stripeToken'] not being populated generally occurs when your code isn't creating a Token object via Stripe Checkout prior to running this bit of code.
I would suggest that you check your Stripe account's API logs (https://dashboard.stripe.com/test/logs/overview) and ensure that you are in fact correctly creating a Token object via Stripe Checkout prior to calling this create Charge snippet.
You may also want to read through their Checkout PHP tutorial (https://stripe.com/docs/checkout/php), to get a better understanding of how all of the pieces fit together. If you still have issues after all that, you may want to write in to their support staff via https://support.stripe.com/email since you probably don't want to discuss private account specific things in public.
This is a quick finding I just experienced. If you're using the default <form action="/directory" method="POST"> ... </form> from this stripe example page with your own endpoint make sure to specify down to the index.php file inside the directory folder.
I was getting an odd error where the token was being created but I would get directed to the PHP endpoint and it wasn't a POST event. I had an index.php file in /directory/ and I had to write the complete path not just up to /directory eg. /directory/index.php. Then it worked as expected.
I want to confirm and extend what subalublub said, in that the endpoint can simply be "/charge/" without having to use index.php there.
I ran into this issue and just using "/charge" was not passing in the $_POST values, but when changing to "/charge/" the index.php file inside that folder worked correctly.
Hope this helps someone.

Security for an AngularJs + ServiceStack App

I have an application that have four modules in the front end, I'm trying to use as much as possible AngularJs in the front end I'm using an empty website asp.net project to host all the files and the REST serviceStack, my project have kind of the following structure:
~/ (web.config, global.asax and all the out of the box structure for an asp.net website)
- App <- AngularJs
- Users <- js controllers and views (static html files)
- Companies
- BackEnd
- Public
Index.html
IndexCtrl.js
App.js
- Content
- Js
I use angularjs service calls and the backend I'm using REST with servicestack.
the question is how can I restrict the access only to authenticated users to those static html files? let's say the ones that are inside inside Companies, Backend and users for example
Hi After doing some research this is the solution that worked for me:
Install razor markdown from nuget
Change the file structure to match the default behavior RM [Razor Markdown] to /views
Modify the web config following the approach described in this service stack example
Change all the static htmls files to .cshtml files, this by default creates the same route without the extension like /views/{Pagename} without the extension, I'm just using this approach to get the authorization logic simpler to implement (at least for me)
Update the service method with an authorize attribute you can find out more in this page
to illustrate a lit of bit more this is my route definition in so far:
'use strict';
angular.module('myApp', ['myApp.directives', 'myApp.services']).config(
['$routeProvider', function($routeProvider) {
$routeProvider.when('/Dashboard', {
controller: 'dashboardCtrl',
templateUrl: 'Views/dashboard'
}).when('/Payments', {
controller: 'paymentsCtrl',
templateUrl: 'Views/payments'
}).
when('/Login', {
controller: 'loginCtrl',
templateUrl: 'Views/login'
});
}]
);
Notice that the references are pointed now to the razor paths.
this is a small menu I've done in angular
<div class="container">
<div class="navbar" ng-controller="indexCtrl">
<div class="navbar-inner">
<a class="brand" href="#/">header menu</a>
<ul class="nav">
<li ng-class="{active: routeIs('/Dashboard')}">Dashboard</li>
<li ng-class="{active: routeIs('/Login')}">Login</li>
<li ng-class="{active: routeIs('/Payments')}">payments</li>
</ul>
</div>
</div>
<ng-view></ng-view>
</div>
let's say that the payments page is restricted, so every time I click on a the page I get a 401 unauthorized message.
Service host:
public override void Configure(Container container)
{
Plugins.Add(new AuthFeature(() => new AuthUserSession(), new IAuthProvider[] {
new FacebookAuthProvider(appSettings),
new TwitterAuthProvider(appSettings),
new BasicAuthProvider(appSettings),
new GoogleOpenIdOAuthProvider(appSettings),
new CredentialsAuthProvider()
})); //I'm going to support social auth as well.
Plugins.Add(new RegistrationFeature());
Routes.Add<UserRequest>("/Api/User/{Id}");
Routes.Add<LoginRequest>("/Api/User/login","POST");
Routes.Add<PaymentRequest>("/views/Payments");
}
I hope that helps
Create a CatchAllHander method to check for restricted routes and, for those static files that require authentication, return the ForbiddenFileHander if not authenticated, otherwise return null. Given an isAuthenticated method and restrictedDirs is defined somewhere - maybe your app or web config file, it can be as simple as:
appHost.CatchAllHandlers.Add((httpMethod, pathInfo, filePath) => {
if ( restrictedDirs.ContainsKey(pathInfo) && !isAuthenticated())
return new ForbiddenHttpHandler();
return null;
});
Why not use Forms Authentication? Simply add a few < location > tags to your web.config to allow/disallow different sections, you can even do it based on roles.

Resources