I’m using Passport for my authentication system.
I’m not sure why Auth::check()
‘s returning false
even though I’m using the correct credentials to login. I can verify that the login works because if I type in a wrong email and password, the login fails.
I’ve been stuck on this for a few days and not sure what’s wrong.
public function login(Request $request) {
$user = User::where('email', $request->email)->firstOrFail();
if (Hash::check($request->password, $user->password)) {
$loginToken = $user->createToken('MyApp')->accessToken;
dd(Auth::check());
return response()->json([
'message' => 'Successfully logged in',
'loginToken' => $loginToken
]);
}
return $this->sendError('Unauthorized.', ['error' => 'Unauthorized']);
}
Here’s api.php
:
Route::group(['middleware' => 'api'], function(){
Route::post('/login', [RegisterController::class, 'login']);
});
Here’s auth.php
:
'defaults' => [
'guard' => 'api',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],
Here’s login:
const handleSubmitLogin = (e) => {
e.preventDefault();
let dataLogin = {
'email': email,
'password': password,
};
JSON.stringify(dataLogin);
axios.post('http://site.test/api/login', dataLogin)
.then(resp => {
console.log(resp);
history.push('/gallery');
}).catch(error => {
console.log(error);
});
setUserState('myState');
};
dd() response:
IlluminateHttpClientResponse {#329
#response: GuzzleHttpPsr7Response {#365
-reasonPhrase: "Unauthorized"
-statusCode: 401
-headers: array:8 [
"Server" => array:1 [
0 => "nginx/1.18.0 (Ubuntu)"
]
"Content-Type" => array:1 [
0 => "application/json"
]
"Transfer-Encoding" => array:1 [
0 => "chunked"
]
"Connection" => array:1 [
0 => "keep-alive"
]
"Cache-Control" => array:1 [
0 => "no-cache, private"
]
"Date" => array:1 [
0 => "Sun, 26 Sep 2021 16:06:57 GMT"
]
"X-RateLimit-Limit" => array:1 [
0 => "60"
]
"X-RateLimit-Remaining" => array:1 [
0 => "57"
]
]
-headerNames: array:8 [
"server" => "Server"
"content-type" => "Content-Type"
"transfer-encoding" => "Transfer-Encoding"
"connection" => "Connection"
"cache-control" => "Cache-Control"
"date" => "Date"
"x-ratelimit-limit" => "X-RateLimit-Limit"
"x-ratelimit-remaining" => "X-RateLimit-Remaining"
]
-protocol: "1.1"
-stream: GuzzleHttpPsr7Stream {#363
-stream: stream resource @9
wrapper_type: "PHP"
stream_type: "TEMP"
mode: "w+b"
unread_bytes: 0
seekable: true
uri: "php://temp"
options: []
}
-size: null
-seekable: true
-readable: true
-writable: true
-uri: "php://temp"
-customMetadata: []
}
}
#decoded: null
+"cookies": GuzzleHttpCookieCookieJar {#343
-cookies: []
-strictMode: false
}
+"transferStats": GuzzleHttpTransferStats {#364
-request: GuzzleHttpPsr7Request {#359
-method: "POST"
-requestTarget: null
-uri: GuzzleHttpPsr7Uri {#349
-scheme: "http"
-userInfo: ""
-host: "site.test"
-port: null
-path: "/oauth/token"
-query: ""
-fragment: ""
}
-headers: array:4 [
"Content-Length" => array:1 [
0 => "115"
]
"User-Agent" => array:1 [
0 => "GuzzleHttp/7"
]
"Host" => array:1 [
0 => "site.test"
]
"Content-Type" => array:1 [
0 => "application/x-www-form-urlencoded"
]
]
-headerNames: array:4 [
"content-length" => "Content-Length"
"user-agent" => "User-Agent"
"host" => "Host"
"content-type" => "Content-Type"
]
-protocol: "1.1"
-stream: GuzzleHttpPsr7Stream {#350
-stream: stream resource @7
wrapper_type: "PHP"
stream_type: "TEMP"
mode: "w+b"
unread_bytes: 0
seekable: true
uri: "php://temp"
options: []
}
-size: 115
-seekable: true
-readable: true
-writable: true
-uri: "php://temp"
-customMetadata: []
}
}
-response: GuzzleHttpPsr7Response {#365}
-transferTime: 0.080212
-handlerStats: array:38 [
"url" => "http://site.test/oauth/token"
"content_type" => "application/json"
"http_code" => 401
"header_size" => 265
"request_size" => 260
"filetime" => -1
"ssl_verify_result" => 0
"redirect_count" => 0
"total_time" => 0.080212
"namelookup_time" => 0.000237
"connect_time" => 0.00033
"pretransfer_time" => 0.000366
"size_upload" => 115.0
"size_download" => 118.0
"speed_download" => 1475.0
"speed_upload" => 1437.0
"download_content_length" => -1.0
"upload_content_length" => 115.0
"starttransfer_time" => 0.078857
"redirect_time" => 0.0
"redirect_url" => ""
"primary_ip" => "127.0.0.1"
"certinfo" => []
"primary_port" => 80
"local_ip" => "127.0.0.1"
"local_port" => 59814
"http_version" => 2
"protocol" => 1
"ssl_verifyresult" => 0
"scheme" => "HTTP"
"appconnect_time_us" => 0
"connect_time_us" => 330
"namelookup_time_us" => 237
"pretransfer_time_us" => 366
"redirect_time_us" => 0
"starttransfer_time_us" => 78857
"total_time_us" => 80212
"appconnect_time" => 0.0
]
-handlerErrorData: 0
}
}
2
Answers
Technically you are not logged in at this point.
You have checked that the user exists, then you have created a new token for this user, but that’s all, the token has not been used to authenticate anyone.
In order to authenticate the user, you will need to make a request with the
Authorization
header setup:Authorization: Bearer $the_token_you_created
.The usual workflow for api tokens is:
However, you are using Passport… which don’t make sense since you don’t seem to need OAuth2 support. You should better take a look at Sanctum with api tokens.
Besides @Anthony Aslangul answer is right, I see that your login is not correct.
As per Laravel Passport Documentation
Saying that, the right way to login should be like this, withing your login function
In addition, in order to check if your user is logged in, you can try by specifying your guard such as
These also may help you:
how to check if user is authenticated with passport (get user from token using laravel-passport)
Laravel Passport Token doesn't return series of code