TransWikia.com

Laravel 6 - auth()->user()||Auth::user() not working on a route where verifycsrfToken middleware is disabled, return empty object

Stack Overflow Asked by Simon Angatia on December 11, 2020

I have two methods in the same controller. Now, one of the routes handles the POST requests from an API and I had to disable the VerifyCsrfToken middleware because it wasn’t receiving data then, and since it is a callback URL, it has to receive data in order to save or do something to the data. Before I disabled the VerifyCsrfToken middleware on the route, the POST request was throwing an error that the page expired. This worked when I disabled the middleware though. Now this developed yet another problem, I can’t access the current logged in user through auth()->user()||Auth::user();, it returns an empty object yet I can access the logged-in user from the other methods on the same controller. Whoever knows any solution to this problem?

One Answer

The answer is that you will not be able to get an authenticated user from Auth::user() because there isn't one for this request.

The only way you would be able to find any User from this request would be if there was some identifying information in the POST request from the other server that you could then use to match to a User yourself.

To make this even simpler:

If you log into your website, then I (from a completely different host and client) send a request to your server am I now authenticated as you? NO

This is the same exact thing happening here.

Also:

This route shouldn't have the web group of middleware assigned to it since it is not using sessions. This group is what does the CSRF token check as well (which is session based). Might be better in api.php but would require updating the other server with a different URL unless you change the prefix for the API routes.

Answered by lagbox on December 11, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP