Magic Link login with Laravel Sanctum

4.1k views Asked by At

For my project I have a set of users that should only be able to login by requesting a Magic Link. So they have an email address but no password. To avoid security issues, my goal was to get this working without having to save an authentication token in LocalStorage.

I've tried setting this up the following way with Laravel Sanctum:

  1. When requested, I create a token for the user and email them the plaintext version.
  2. The user would open the link containing the token in the querystring.
  3. I would attach the (Bearer) token with the Authorization Header.
  4. The next step (I assumed) would be to call a custom /api/login endpoint that uses the 'auth:sanctum' middleware. The Bearer token would authenticate the user and then I would manually login the user with Auth::login(). After this the active Session would be used to authenticate the user, thus avoiding having to save the token in localStorage.

But I can't call the Auth::login() method manually without getting an error (BadMethodCallException: Method Illuminate\Auth\RequestGuard::login does not exist.).

I can't figure out why this isn't working, or maybe I am going at this all wrong?

1

There are 1 answers

5
Kamlesh Paul On BEST ANSWER

if you sending Sanctum token to user via email so in 1st request you will get token from url and you can use that token to login to application like this

use Laravel\Sanctum\PersonalAccessToken;
public function login(Request $request)
{
    $personalAccessToken = PersonalAccessToken::findToken($request->token);
    $user = $personalAccessToken->tokenable;
    auth()->login($user);
    return redirect('/');
}