Laravel 5.7 tokenmismatch error when trying to post form - laravel

I'm running laravel 5.7, I changed the sessions to the database. I did make:auth and tried to register and got an error page with
"The page has expired due to inactivity. Please refresh and try again"
I have been at this for a couple of days now. I added /register to the except array to bypass the verify token and was able to register. Now I'm trying to login and get the same issue. I have **cleared cache, checked settings, switched back to file, tried other browsers, verified the token was in the form, make sure it was in the header, made sure it was getting passed and still nothing. I added this to the Handler class in Exceptions:
if ($exception instanceof \Illuminate\Session\TokenMismatchException) {
return redirect()->back()->with('error_message',"Oops! Seems there was an error with login. Please try again or contact us.");
}
and this leaves me to believe the token is not matching because it redirects instead of going to the broken page. I have read through I think every article on the internet and cannot figure this out. My next option is to start fresh with a new install unless anyone has any idea what could cause this?
This was on my local. I have not pushed anything to production.
Edited to add Form:
{!! Form::open(['route' => 'login', 'method' => 'post']) !!}
<div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
<label for="email" class="col-md-4 control-label">E-Mail Address</label>
<div class="col-md-12">
<input id="email" type="email" class="form-control" name="email" value="{{ old('email') }}" required autofocus>
#if ($errors->has('email'))
<span class="help-block">
<strong>{{ $errors->first('email') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group{{ $errors->has('password') ? ' has-error' : '' }}">
<label for="password" class="col-md-4 control-label">Password</label>
<div class="col-md-12">
<input id="password" type="password" class="form-control" name="password" required>
#if ($errors->has('password'))
<span class="help-block">
<strong>{{ $errors->first('password') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group">
<div class="col-md-6 offset-md-4">
<div class="checkbox">
<label>
<input type="checkbox" name="remember" {{ old('remember') ? 'checked' : '' }}> Remember Me
</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-8 offset-md-4">
<button type="submit" class="btn btn-primary">Login </button>
<a class="btn btn-link" href="{{ route('password.request') }}">
Forgot Your Password?
</a>
</div>
</div>
{!! Form::close() !!}

Try using a different browser to login or an incognito window.
Also remember on any form where you are POST-ing to use the #csrf in your blade file.

This problem comes from CSRF token validation which fails:
'The page has expired due to inactivity. Please refresh and try
again.'
you should include a hidden CSRF token field in the form so that the CSRF protection middleware can validate the request.
<form method="POST" action="/profile">
#csrf
...
</form>
It doesn't work, then Refresh the browser cache and now it might work

There should not accure any errors, so if you only want to create the auth scaffolding I would suggest just to create a new laravel project.
Do following steps:
laravel new app
create the database
Add the database credentials to your .env file
run php artisan:migrate in your command line, inside your project, that should create you a users table
run php artisan make:auth, that is going to create the basic auth logic
Lastly run php artisan migrate again

In case someone in the future comes here and tries all the solutions out there and they dont work I wanted to share what finally worked for me. I started by installing a new instance of laravel 5.8. I did make:auth and checked that the standard forms works as expected. I then added in the code from the instance that was not working which was basically my custom app.blade.php, header.blade.php,footer.blade.php,welcome.blade.php register.blade.php, helpers.php ( contains my custom helper functions ) and updated composer.json with the packages I use. I ran composer update and it did not work. I went back to the beginning and added each piece individually until I found the issue. I am not sure why this happened but the issue was this:
I have a custom file within app/ called helpers.php. I add it via composer.json like this:
"autoload": {
"classmap": [
"database/seeds",
"database/factories"
],
"psr-4": {
"App\\": "app/"
},
"files": [
"app/Http/helpers.php"
]
},
I have one function in there that I use to wrap files in that adds in my aws S3 endpoint. Thats it. But for some reason this was causing the site to redirect on every page load back to itself and give me a new session. I would refresh over and over and just watch the session files accumulate. I read that the helper functions are getting deprecated in 5.9 so I went ahead and created a provider then use that in place of my helper function which did the trick.
If someone knows why this happens I would love to hear it. But if you have this issue, open up the sessions folder in your editor and see if you keep getting new sessions. If so then backtrack and see whats causing it to reroute.

Related

Why I keep getting Error 419 Page expired

I am using laravel 7 and keep having this issue in my form:
<form class="form-inline " role="form" method="POST" action="{{route('auth.signup')}}">
<input type="hidden" name="_token" value="{{csrf_token()}}">
<div class="form-group">
<input type="email" class="form-control" id="inputEmail" name="email" value="email">
</div>
<div class="form-group">
<input type="password" class="form-control" id="password1" name="password">
</div>
<div class="form-group">
<input type="password" class="form-control" id="password2" name="password_confirmation">
</div>
<button type="submit" class="btn btn-primary mx-auto">Sign Up</button>
</form>
i already have changed config/session.php This line 'lifetime' => env('SESSION_LIFETIME', 1200),
Is it necessary to show route / controller they all just basic
I have also tried to remove the controller's entire code and simply dd("signed up") but i keep getting the same issues
I also went on to change my php.ini file but the problem persists.
maybe another piece of information to add is that the homepage which has the signup link to the form above also has its own form with a and its not the same token as the one in the form above
The sign up controller:
public function postSignup(Request $request)
{
$this->validate($request,[
'email'=>'required|unique:appscheduler_users|email|max:255',
'name'=>'required|max:255',
'password'=>'required|confirmed|min:6',
]);
$user=user::create([
'email'=>$request->input('email'),
'name'=>$request->input('name'),
'password'=>bcrypt($request->input('password')),
'created'=>date('Y-m-d H:i:s'),
'ip'=>$request->ip(),
]);
Auth::login($user);
if(Session::has('oldUrl')) {
$oldUrl=Session::get('oldUrl');
Session::forget('oldUrl');
return redirect()->to($oldUrl);
}
return redirect()
->route('home')
->with('info','Your Account has been created');
}
To solve this error you first need to insert one of the following commands into the form tag.
#csrf OR {{ csrf_field }}
If your problem is not resolved, do the following: and keep the csrf tag
1.Insert one of the following commands into the form tag #csrf OR {{ csrf_field }}
2.Open the .env file and change the values ​​to the "file" in the SESSION_DRIVER section.
3.Then you should reset laravel cache. type below commands in the terminal
php artisan view:clear php artisan route:clear php artisan cache:clear
php artisan config:cache
4.In the final step, unplug the project from the serve and click again on php artisan serve
I hope your problem is resolved
maybe you wanna take a look here
Post request in Laravel - Error - 419 Sorry, your session has expired

The PUT method is not supported for this route. Supported methods: GET, HEAD

I'm trying to learn Laravel, and I'm following a series of tutorials called laracast. I'm at episode 24, "Forms that submit PUT requests. The short story is that the markup uses a hidden value to set the method to PUT, although the forms method is set to POST. Still, when I do this, I get the error message from the title:
Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException
The PUT method is not supported for this route. Supported methods: GET, HEAD.
From the tutorials, I'd expect POST to also be a supported method. However, when I try to fix this, all resources I can find simply tells me what I already know. PUT is not supported, but I can fake it/override it, and then they refer to what I have already done... Are there any other reasons why I might get this error message?
HTML Form:
<form method="POST" action="/competition-categories">
#csrf
#method('PUT')
<div class="form-group row">
<label for="competition-category-name-input" class="col-4 col-form-label">Name</label>
<div class="col-8">
<input id="competition-category-name-input" name="competition-category-name-input" type="text" class="form-control" required="required" value="{{ $competitionCategory->name }}">
</div>
</div>
<div class="form-group row">
<label for="competition-category-abbreviation-input" class="col-4 col-form-label">Abbreviation</label>
<div class="col-8">
<input id="competition-category-abbreviation-input" name="competition-category-abbreviation-input" type="text" class="form-control" required="required" value="{{ $competitionCategory->abbreviation }}">
</div>
</div>
<div class="form-group row">
<div class="offset-4 col-8">
<button name="submit" type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
web.php snippet:
//Competition Categories
Route::get('/competition-categories', 'CompetitionCategoryController#index');
Route::get('/competition-categories/create', 'CompetitionCategoryController#create');
Route::get('/competition-categories/{competitionCategory}', 'CompetitionCategoryController#show');
Route::get('/competition-categories/{competitionCategory}/edit', 'CompetitionCategoryController#edit');
Route::post('/competition-categories/{competitionCategory}', 'CompetitionCategoryController#store');
Route::put('/competition-categories/{competitionCategory}', 'CompetitionCategoryController#udpate');
Route::delete('/competition-categories/{competitionCategory}', 'CompetitionCategoryController#destroy');
Snippet from the controller:
public function update(Request $request, CompetitionCategory $competitionCategory)
{
$competitionCategory->update($this->validateCompetitionCategory());
return redirect()->route('competition-categories' , [$competitionCategory]);
}
You're forgetting the id in form, this should fix your problem:
action="/competition-categories/{{$competitionCategory->id}}"
The most common thing that this happens is your cache. When you add a new route or change something in your routes, always run after php artisan optimize to refresh you cache.
I recommend using the named-routes for more informations and messages see =>
https://laravel.com/docs/7.x/routing#named-routes

This password reset token is invalid while trying to reset password in laravel

I am having issue in my password reset and i am getting the error of this password reset token is invalid i am unable to solve this issue:
My Controller:
class ResetPasswordController extends Controller
{
use ResetsPasswords;
}
My Routes:
\Illuminate\Support\Facades\Auth::routes();
Route::get('password/reset/{token}', 'Auth\ResetPasswordController#showResetForm');
Route::post('password/reset', 'Auth\ResetPasswordController#reset')->name('password.request');
And my View:
<form class="form-horizontal" method="POST" action="{{ route('password.request') }}">
{{ csrf_field() }}
<input type="hidden" name="token" value="{{ $token }}">
<div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
<label for="email" class="col-md-4 control-label">E-Mail Address</label>
<div class="col-md-6">
<input id="email" type="email" class="form-control" name="email" value="{{ $email or old('email') }}" required autofocus>
#if ($errors->has('email'))
<span class="help-block">
<strong>{{ $errors->first('email') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group{{ $errors->has('password') ? ' has-error' : '' }}">
<label for="password" class="col-md-4 control-label">Password</label>
<div class="col-md-6">
<input id="password" type="password" class="form-control" name="password" required>
#if ($errors->has('password'))
<span class="help-block">
<strong>{{ $errors->first('password') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group{{ $errors->has('password_confirmation') ? ' has-error' : '' }}">
<label for="password-confirm" class="col-md-4 control-label">Confirm Password</label>
<div class="col-md-6">
<input id="password-confirm" type="password" class="form-control" name="password_confirmation" required>
#if ($errors->has('password_confirmation'))
<span class="help-block">
<strong>{{ $errors->first('password_confirmation') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary">
Reset Password
</button>
</div>
</div>
</form>
I have also added the screen shot of my error please have a look on it also
and solution will be highly appreciated!
I has solved this problem with Laravel 7.x. I think Laravel 6.x is the same!
I create a variable $token = Str::random(64);
Next I create a record in password_resets table with value of token is: bcrypt($token)
( bcrypt() is function create password when you seed database)
Finally, link you send to email is origin $token
Because your token is incorrect, it should be a string length of 64 characters and look like this:
a8935edacb0711a304395c1f58979b545b4a636387053de6012e73048e5a60d2
And in your password_resets table in your database, it should be encrypted and look like this:
$2y$10$YOdbMZk2N7xLsfXZIuMIv.ZayZQCB21L.GXVPdtt/WMOO1hJL7enO
Change your MAIL_DRIVER= to log, truncate password_resets table (if on local), then do another password reset, then check your logs to read the email and see what the password reset token is. Copy and paste that url in your browser and see if you still get that error then we take it from there. :)
I got this issue resolved by running migrations. The password reset token column had the wrong type. It was not storing token correctly due to the wrong charset/collation of the column. Run migration and it should be fine.
or
maybe your reset password form does not contain an input for email
I had a different issue.
My passwords configuration in auth.php looks like this:
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => env('AUTH_PASSWORD_EXPIRE')
],
],
But I forgot to configure the AUTH_PASSWORD_EXPIRE .env variable on my live server.
In my case, the issue was the users table. I created the users table manually with my custom fields prior to installing laravel breeze and added the breeze required fields manually to table. I did not used breeze migration. That caused the issue.
Now I run breeze migration to create users table and then added my custom fields manually. It solved the issue.
You should also check which hash function you are using while registering the user, if the hash function for storing the user password while resetting is different from the one used to login the user you might recieve this error. In my case one was using bcrypt and one was using Hash::make

Laravel: Show HTML Code and Laravel Syntax from Database?

in my App I have a table (cats) with 30 categories. The Table "cats" has a name and code field. Every Category needs different forms. To be more flexible and to make the code simpler, I am saving the HTML Code for the different forms directly into the Database.
I am able to fetch the content with:
{!! $cats->code !!}
The Content of the DB Field:
<label for="textfield">Text Field:</label>
<input type="text" name="textfield" id="textfield">
Well, with that simple code, everything runs fine, the HTML Syntax will be shown.
Now I tried with that Code, but this is not working. I think it could be, because I am mixing html with laravel syntax...
<div class="form-group row">
<label for="email" class="col-sm-4 col-form-label text-md-right">{{ __('E-Mail Address') }}</label>
<div class="col-md-6">
<input id="email" type="email" class="form-control{{ $errors->has('email') ? ' is-invalid' : '' }}" name="email" value="{{ old('email') }}" required autofocus>
#if ($errors->has('email'))
<span class="invalid-feedback">
<strong>{{ $errors->first('email') }}</strong>
</span>
#endif
</div>
</div>
Has anyone an idea how to solve this issue?
Kind Regards
Stefan
It won't work. Your blade views are parsed to HTML with PHP before any code is run. So Laravel will eventually just echo the blade code, but it is not getting parsed at that stage of your app.
A solution would be to wrap everything in PHP and use eval to have dynamic content stored in the database. This makes it a little bit more of an effort, but it is certainly possible.

Laravel 5.3 - TokenMismatchException on every post request

I was working on my project normally and when i hit refresh to see a change that i just made in one of the html pages, the page showed a text on top left "Redirecting to: http://localhost:8888/xxx ". It redirected me to the login page. When i clicked login, the 'TokenMismatchException' error showed:
The login form has the hidden input _token , header has it too. As i said everything was fine. I have been working on this project for 2 months. Is this related to files permissions ?
Here is the login form.
<form class="form-horizontal" role="form" method="POST" action="{{ url('/login') }}">
{{ csrf_field() }}
<div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
<label for="email" class="col-md-4 control-label">E-Mail Address</label>
<div class="col-md-7">
<input id="email" type="email" class="form-control" name="email" value="{{ old('email') }}" required autofocus>
#if ($errors->has('email'))
<span class="help-block">
<strong>{{ $errors->first('email') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group{{ $errors->has('password') ? ' has-error' : '' }}">
<label for="password" class="col-md-4 control-label">Password</label>
<div class="col-md-7">
<input id="password" type="password" class="form-control" name="password" required>
#if ($errors->has('password'))
<span class="help-block">
<strong>{{ $errors->first('password') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group">
<div class="col-md-8 col-md-offset-4">
<button type="submit" class="btn btn-primary">
Login
</button>
<a class="btn btn-link" href="{{ url('/password/reset') }}">
Forgot Your Password?
</a>
</div>
</div>
</form>
Thanks :)
After i installed a fresh laravel copy i started to paste my old files to see where would regenerate the mismatch token problem.
It went down to the routes/web.php file. Something there was causing the error. It was a space before the opening tag of php on routes/web.php file.
Something that did not caught my eye. Like that the project was working fine but suddenly did not anymore.
As i read , the space is considered an output. Check this explanation :
https://stackoverflow.com/a/4345822/6634389
Why don't you use {{ csrf_field() }} or try with that?
Run:
php artisan cache:clear; composer dump-autoload; composer clear-cache
Refresh the browser, make sure you generated the key for your app. This should work. For me it did.
You are refreshing your page, so each time the pages load with same csrf-token. So when you are trying to post your data, laravel refuses it and provide error message due to each request should have a unique csrf-token. You can read about this herelaravekl csrf protection
Either you should again reload your page or you should disable the csrf protection by commenting it inside the
App=>Http=>Kernel.php
inside the $middlewareGroups=>'web'
\App\Http\Middleware\VerifyCsrfToken::class, //comment this line
I was having the same issue, I solved it by using following in my view
<input type="hidden" name="_token" value="{{ session()->getToken() }}">

Resources