After i register an user using the passport and see the user in database. i tried to login and i get the message "Unauthorised". this is my login method:
public function login(){
if(Auth::attempt(['email' => request('email'), 'password' => request('password')])){
$user = Auth::user();
$success['token'] = $user->createToken('MyApp')->accessToken;
return response()->json(['success' => $success], $this->successStatus);
}
else{
return response()->json(['error'=>'Unauthorised'], 401);
}
}
i also tried to receive the Request in the login method as a parameter and handle it but i still do not login.
I'm using Postman to perform the request
[update]
i checked that my request() is receiving null
You can add those parameters in request body as JSON
data like below
{
"email":"test@mail.com",
"password":"123456"
}
also add Content-Type:application/json
to your request header.
then need a little bit change in your login()
method to accept the JSON
data received
public function login(Request $request){
if(Auth::attempt(['email' => $request->json('email'), 'password' => $request->json('password')])){
$user = Auth::user();
$success['token'] = $user->createToken('MyApp')->accessToken;
return response()->json(['success' => $success], $this->successStatus);
}
else{
return response()->json(['error'=>'Unauthorised'], 401);
}
}
Response:-
{
"success": {
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6IjAzZDA1YzRiMmRhNTc3YmQ4ZTliMTRlZjE3MWRlYWIyOTI2NTJjNjg2MDY2ZmU1ZjYzM2ZiZjBjNTc3YTM0MGM1NDUxOTczZTYxZmFjMjIzIn0.eyJhdWQiOiIxIiwianRpIjoiMDNkMDVjNGIyZGE1NzdiZDhlOWIxNGVmMTcxZGVhYjI5MjY1MmM2ODYwNjZmZTVmNjMzZmJmMGM1NzdhMzQwYzU0NTE5NzNlNjFmYWMyMjMiLCJpYXQiOjE1MTExMDcwNzAsIm5iZiI6MTUxMTEwNzA3MCwiZXhwIjoxNTQyNjQzMDcwLCJzdWIiOiIxIiwic2NvcGVzIjpbXX0.GrFth1I7PnkT7FOSQkkUEl0uc3CddUVEAgMHwFlKIIiC740B-Eu3-73IrYEH-VYXeWrZKP9FaK2lL_QR7wpZXnP20e5q4OoznVg0kqE5DsfsFw8lywUtPF7so4QcxcU3wFUKWGl4nEDTaiAJtU4UJnBcaG6Xj98jqEsGIkY9fboOI2bpbQ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