php - How to see if you are logged in laravel api
Get the solution ↓↓↓TheresAuth::check
andauth('api')->check()
but if you use a token, and you go to the console, application tab and click cookies and blow away the laravel session, then try and make an api call usingauth:api
as the middleware with token based check, you can still do api requests.
I am unsure how to NOT allow you to do this, I attempted to create a middleware that would check if you are physically logged into the system in order to do api calls, regardless of the fact that you have a token but it seems to state thatAuth::check
is true, and theauth()->user()
returns a user when that middleware in question is hit when doing api calls while you have no session.
For example heres the middleware:
<?php
....
class IsCharacterLoggedInMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null $guard
* @return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
dump(auth()->user(), auth('api')->check(), Auth::check()); // Returns: user object, true, true - even though I have no session.
if (!Auth::check()) {
dd(auth()->user());
return event(new RefreshUserScreenEvent(auth()->user()));
}
return $next($request);
}
}
If I then use this inRoute::middleware([...])
around an api call, go to the console, application -> cookies, blow awaylaravel_session
and then hit the api end point, the api request succeeds.
But if I then refresh, I am back on the login page.
In the config section I use:
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
'hash' => true,
'input_key' => 'private_game_key',
'storage_key' => 'game_key',
],
],
As you can see for api I use tokens. But I also want to use session to say: Ok you have a vlid key, but you are not physically logged in.
How do I check for a valid session when making an api call? All my google searches say to use:Auth::check()
But is that right am I doing something wrong?
Answer
Solution:
Token auth is meant not having to keep sessions alive,
but one can still use thesession
driver, when required:
'api' => [
'driver' => 'session',
...
],
Or alternatively, useweb
routes with thesession
driver.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: the payload is invalid.
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.