I am facing a problem where when I tried to login in postman, the data return after login is not a bearer token but such like this
{
"success": true,
"message": "User login succesfully, Use token to authenticate.",
"token": {
"name": "passport_token",
"abilities": [
"*"
],
"tokenable_id": 1,
"tokenable_type": "App\\Models\\User",
"updated_at": "2022-07-04T08:52:22.000000Z",
"created_at": "2022-07-04T08:52:22.000000Z",
"id": 6
}
}
Below is the login API
public function login(Request $request)
{
$input = $request->only(['email', 'password']);
$validate_data = [
'email' => 'required|email',
'password' => 'required|min:8',
];
$validator = Validator::make($input, $validate_data);
if ($validator->fails()) {
return response()->json([
'success' => false,
'message' => 'Please see errors parameter for all errors.',
'errors' => $validator->errors()
]);
}
// authentication attempt
if (auth()->attempt($input)) {
$token = auth()->user()->createToken('passport_token')->accessToken;
return response()->json([
'success' => true,
'message' => 'User login succesfully, Use token to authenticate.',
'token' => $token
], 200);
} else {
return response()->json([
'success' => false,
'message' => 'User authentication failed.'
], 401);
}
}
How to get the bearer token instead of the json like that since I also not found the way in documentation.
CodePudding user response:
Try change accessToken
to plainTextToken
-------
$token = auth()->user()->createToken('passport_token')->plainTextToken;
return response()->json([
'success' => true,
'message' => 'User login succesfully, Use token to authenticate.',
'token' => $token,
'tokenType' => 'Bearer'
], 200);
---------
Hope this help you
CodePudding user response:
That's weird behaviour of passport package, even though we follow the documentation. However if you want to generate the token then you can do it by following LOC.
$resultToken = $user->createToken($user->email);