1
votes

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
Auth is only available through middleware, you mentioned using auth:sanctum middleware -- it's enabled in the middleware list yes? One way of going about this is to copy the reset password process, with the exception that instead of changing a password via token, you find the user with that token, and pass their id to the Auth::loginUsingId method. There are many ways of doing this, another example would be similar to SSO where a token can verify a user. If your keen on using sanctum, go through the docs with a fine tooth comb, hope that helps!CodeJunkie
PS are you passing the csrf_token with your fetch/axios/ajax request? Is use Auth; in the guard/controller class?CodeJunkie
how you are using token in header of each request or in url paramter .?Kamlesh Paul
@CodeJunkie How can I find a user by token? I only have the plaintextToken.generator
@CodeJunkie Yes CSRF is working fine. In fact when using the default /login endpoint with a username/password everything is working perfectly.generator

1 Answers

7
votes

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('/');
}