Im building an a hybrid app in cordova and using laravel as api, but im a little bit confused with the Auth:api, I could not find any tuto explaining what I want! I want to know how can a user get authenticated from the app on his phone to my laravel api, as far as I know I am gonna use a api_token (random string), that I am gonna store on Users table, that is fine but how am I gonna authenticate the user with it and how to keep the user sending it with all requests? can I just store it in the app and keep sending it? Im stuck with the login! how to login the user for the first time? Im I gonna use the login provided by laravel or build a new one for this?? help please
For the use of auth:api
guard in Laravel 5.2 see https://andrew.cool/blog/64/How-to-use-API-tokens-for-authentication-in-Laravel-5-2 it seems quite thorough.
Now for the rest of your questions:
For the login you will need an API call that the client will use to login , let's say:
POST logins
with body:
{
"email": "user@example.com",
"password": "password"
}
which in Laravel could represented as:
Route:post('logins', 'MyApiController@login');
Now in the MyApiController::login()
method you will check the credentials provided email
, password
and if they match with a record in your database then you will respond with an api_token
. That api_token can be created on the fly (make it hard to break) or if the user has already an api_token
you can return that one. It depends in your expiration policy, if you want a login to also mean a logout for other devices etc.
If the credentials do not match then you will respond with a 400 Bad Request
and the client in that case should attempt to login again.
For your other question, yes the client app MUST remember the api_token
and include it in every API call that needs it .
Take care that Laravel searches for the api_token
in a specific order as seen from the code below (that is Laravel 5.4). In the link I gave you above there are instructions on how to include the api_token
.
public function getTokenForRequest()
{
$token = $this->request->query($this->inputKey);
if (empty($token)) {
$token = $this->request->input($this->inputKey);
}
if (empty($token)) {
$token = $this->request->bearerToken();
}
if (empty($token)) {
$token = $this->request->getPassword();
}
return $token;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.