4

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 ?

code-8
  • 54,650
  • 106
  • 352
  • 604

3 Answers3

3

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

OsDev
  • 1,243
  • 9
  • 20
3

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
    ]);
}
iHabboush
  • 537
  • 4
  • 8
2

Here's an example of a register controller method that uses Laravel Passport's createToken() method to generate a unique access token. You could use similar functionality to return this token when the user logs in.

public function register(Request $request)
{
    $validator = Validator::make($request->all(), [ 
        'name' => 'required', 
        'email' => 'required|email', 
        'password' => 'required', 
        'retype_password' => 'required|same:password', 
    ]);

    if ($validator->fails()) { 
        return response()->json($validator->errors(), Response::HTTP_FORBIDDEN);            
    }

    $user = User::firstOrCreate(
        ['email' => $request->email],
        ['name' => $request->name, 'password' => bcrypt($request->password)]
    ); 

    $response = [
        'token' => $user->createToken('MyApp')->accessToken
    ];

    return response()->json($response, Response::HTTP_CREATED);
}
Erich
  • 2,408
  • 18
  • 40
  • The back-end API for auth is already existed in NodeJS, I just need to call it, parse it. Do you think I still need a Passport ? – code-8 Aug 23 '19 at 16:16
  • Not if you're using an external auth service. But this example then won't help you. You'll have to implement a different way to get the token from your API. – Erich Aug 23 '19 at 19:08