I have two similiar Laravel project. This is part code of kernel.php. Both projects have same code.
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
],
'api' => [
'throttle:60,1',
],
];
But, VerifyCsrfToken always be called although I put my route inside api middlewareGroup.
I check request header in Advanced REST Client. I found this.
First project result :
Second project result :
First result has cookie attribute in request header, but second result doesn't have
You can skip csrf token check for all your api links in app/Http/Middleware/VerifyCsrfToken.php by adding the URIs to the $except property. Example:
protected $except = [
'/api/*'
];
All the routes in routes.php are included in a route group which has the 'web' middleware applied. You should probably create another routes file and have the RouteServiceProvider load those in a group with 'api' and without the 'web' middleware applied.
If you open up your RouteServiceProvider you will see where this is happening. Check the map method to see it calling mapWebRoutes.
Use routes without any middleware and it will not require csrf token anymore.
Related
I want to ask how can you run the auth middleware before the model binding? Currently in my 5.7 application, model binding is run before the auth. I tried creating a middlwaregroup in kernel.php as follows:
'api' => [
'throttle:10,1',
'jwt.middleware',
'bindings',
],
But still the model binding is run before the auth. Also I tried to change the order of the two middlewares in my route but nothing changed.
The answer is in:
https://laravel.com/docs/5.7/middleware#sorting-middleware
protected $middlewarePriority = [
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\Authenticate::class,
\Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\Auth\Middleware\Authorize::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
];
IF you use explicit bindings, they may run before the auth middleware. In that case, you can use Auth::authenticate() to throw an AuthenticationException which laravel will transform into a redirect to the login page.
Route::bind('user_post', fn ($id) => Auth::authenticate()->posts()->findOrFail($id));
Route::get('posts/{user_post}', ...);
I have added into the exceptions:
protected $except = [
'pay/finish'
];
But still I am getting MethodNotAllowedException
Route is defined in web.php
Route::post('/pay/finish', ['as' => 'pay.finish', 'uses' => 'PaymentController#finish']);
The post request comes from another domain.
You don't normally get a MethodNotAllowedException from an invalid CSRF token. I normally get a 419 response from CSRF issues.
However, assuming the CSRF token is the problem you could move your route from web.php to api.php. Be aware this adds the prefix api/ to the URL.
The middleware that checks the CSRF token is applied in your Kernel to all routes in web.php but not to those is api.php
You could verify whether the CSRF check is really the problem by looking in your App\Http\Kernel file and commenting out \App\Http\Middleware\VerifyCsrfToken::class from:
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
],
'api' => [
'throttle:60,1',
'bindings',
],
];
If your route then works it is CSRF and you can move the route to the API routes file and hit it at api/pay/finish with the api prefix.
If not then I suggest you look at what's calling your route and check the correct http method is being called. Is it definitely sending a POST request?
Do you have the _method input specified in your form that Laravel checks for POST requests to mutate them to PUT or PATCH for its edit routes?
I'm using the default Laravel 5.8 authentication model. It worked fine, but recently I noticed that after I enter the wrong credentials in the login form, it still redirects me to the homepage, and in the corner the browser asks me if I want to save password and etc. Everything looks like I was logged in, but I'm not.
If I enter the correct information, then I get logged in and everything works fine.
I was looking for a solution, but everything I could find was modifying LoginController and RegisterController, and I think I don't want to do that, because default behavior is what I need. So the problem must be somewhere else.
I don't know what code to show. My best guess of what could be related is:
web.php
Route::get('logout', 'Auth\LoginController#logout');
Auth::routes(['verify' => true]);
app/Http/Kernel.php middleware groups
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'admin' => [
\App\Http\Middleware\Administrator::class,
],
'api' => [
'throttle:60,1',
'bindings',
],
];
What I expect: to be redirected back to the same page after an incorrect login/registration.
Problem was that I had this
<meta name=“referrer" content=“origin”>
in my html
I am developing a Laravel application. Now, I am trying to create a middleware that is checked before any routes are registered. Logically, this is what I am trying to do. I have a list of routes saved in the database. Imaging, there is a model called Redirection for it. In the middleware, I want to check, if the requested path falls into one of the redirections in the database, I will redirect to a different path. Now, I created a middleware called RedirectMiddleware. Then I registered it in the kernel class like this,
protected $middlewareGroups = [
'web' => [
RedirectMiddleware::class,
],
'api' => [
//other stuff
],
];
The problem is that when I access the route that does not exist, it renders the 404 error page without going through the middleware first. How can I create/ register a middleware which is called before any routes are registered? Or what could be the better approach to achieve what I want to achieve instead of using middleware?
In Laravel the HTTP Kernel handles the middleware registration. But to register it you have to enter the configuration as you have. In the registration in picks up the desired configuration from the App\Http\Kernel.php. In there, we need to pay attention to our namespace. Laravel only reads what is in the App\Http namespace. When you call your middleware, you are attempting to reference it in relativity as if it is within the current namespace.
protected $middlewareGroups = [
'web' => [
RedirectMiddleware::class,
],
'api' => [
//other stuff
],
];
What you need to be doing is referencing it directly. To do this you need to escape the namespace and give the path. Like so...
protected $middlewareGroups = [
'web' => [
// Your other middlewares
\App\Http\Middleware\RedirectMiddleware::class,
],
'api' => [
//other stuff
],
];
This should solve your issue. If not, let me know and post your middleware so we can see what exactly you are doing.
-- Current Laravel Docs 07/19/2019 :: https://laravel.com/docs/5.8/middleware#registering-middleware
I have a ajax function which call a controller listed on api.php (route).
Inside this controller, I'm trying to make a user's log. So, I need to store the id user in a log table. But, when I try to access any method of Auth::user(), even being logged in, I get the exception "Unauthenticated".
I think It's a miss of sending some header information on ajax function.
Someone could help me, please?
If I am correct, api.php routes in laravel are set to uses tokens rather than the session. This means each call will require a token (specified on the user model/record) to be passed.
Using Auth::user() within web.php will work as that uses user sessions to authenticate.
You can try this one,
In your Kernel.php file add your own name like 'sessions' to the $middlewareGroups. It should contain \Illuminate\Session\Middleware\StartSession::class
Assign 'sessions' to those routes you want.
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
],
'api' => [
'throttle:60,1',
],
'sessions' => [
\Illuminate\Session\Middleware\StartSession::class,
]
];
routes/api.php
Route::group(['middleware' => ['sessions']], function () {
Route::resource(...);
});
I think it must work for you
<?php echo Auth::user() ?>
or {{Auth::user()->(id)}}