I'm using Laravel 5.8, with PHP 7.2.
I need to adjust the way I did the Authentication.
I used to log my users in via my local database from users table.
If the email+password match, I log them in.
$email = strtolower(Input::get('email'));
$password = Input::get('password');
$dbAuth = Auth::attempt(array(
'email' => $email,
'password' => $password,
'active' => 1
));
if ($dbAuth) {
Session::put('user', Auth::user());
return Redirect::to('/dashboard')->with('success', 'You have been successfully logged in.');
} else {
return Redirect::to('/')->with('error', 'Username/Password Wrong')->with('email', $email)->withErrors($validator);
}
Now I need to call /login
API, that will return a token
.
I need to store that token into the local storage on my browser.
I need to make sure my Auth::user()
will work base on change.
How do I start ?
Can someone please shed some lights ?
You can use JWT
Setup jwt after that you can use this code to login and return token :
public function login() {
/// validation
$credentials = request(['email', 'password']);
if (!$token = auth('api')->attempt($credentials)) {
return response()->json(['error' => 'Unauthorized'], 401);
}
return response()->json([
'token' => $token, // Token
'expires' => auth('api')->factory()->getTTL() * 60, // Expiration
]);
}
Use Laravel Passport And then you can do something like this
public function login(Request $request)
{
$request->validate([
'email' => 'required|string|email',
'password' => 'required|string',
'remember_me' => 'boolean',
]);
$credentials = request(['email', 'password']);
if (!Auth::attempt($credentials)) {
return response()->json([
'message' => 'Unauthorized'
], 401);
}
$user = $request->user();
$tokenResult = $user->createToken('Personal Access Token ' . str_random(10));
$token = $tokenResult->token;
if ($request->remember_me) {
$token->expires_at = Carbon::now()->addWeeks(10);
}
$token->save();
return response()->json([
'access_token' => $tokenResult->accessToken,
'token_type' => 'Bearer',
'expires_at' => Carbon::parse(
$tokenResult->token->expires_at)
->toDateTimeString(),
]);
}
this will give you an access token to use in your following requests
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With