Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to log user in via API - Laravel 5.8?

I'm using Laravel 5.8, with PHP 7.2.

I need to adjust the way I did the Authentication.

before

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

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 ?

like image 951
code-8 Avatar asked Jan 26 '23 22:01

code-8


2 Answers

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
    ]);
}
like image 33
iHabboush Avatar answered Jan 28 '23 11:01

iHabboush


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

like image 122
OsDev Avatar answered Jan 28 '23 11:01

OsDev