Laravel Passport API switch user while in development

Viewed 243

I have an Angular 9 SPA with a Laravel 7.x API using Laravel Passport (Personal Access Tokens) for authentication. While in development, every now and then I would like to act as a different user in order to test authentication/permissions. I dont exactly know how to do that cleanly with Laravel Passport.

In the past, when my website was a MPA on Laravel, all I had to do was use Auth::loginUsingId() to act as a different user. Does anyone know of a simple way of switching users server-side without having to deal with logout/login client-side?

UPDATE: So after researching and trying to figure out a custom solution, I ended up creating an AutoLogin middleware to make sure environment was not production and if an AUTO_LOGIN_ID environment variable was set. If true, then I will essentially re-login as the the user I want without credential checks, then send the client the new user and token. Here is my code:

class AutoLoginMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        // Only apply this middleware to non-production environments!!
        if( env('APP_ENV') !== 'production' && env('AUTO_LOGIN_ID') ) {

            // Dont do anything if the autologin user is already logged in
            if( Auth::id() === env('AUTO_LOGIN_ID') ) {
                return $next($request);
            }

            // Set the new user
            $authUser = User::find(env('AUTO_LOGIN_ID'));
            Auth::guard('api')->setUser($authUser);
            $token = Auth::guard('api')->user()->createToken('auth_token')->accessToken;

            // Send the new user information as well as the access token to client.
            return response([
                'user' => Auth::guard('api')->user(),
                'access_token' => $token
            ]);
        }
        return $next($request);
    }
}

So I think that covers the server-side code. The only other thing that I need to figure out is how to properly and securely inform the client that the user has been switched.

Should I send a custom status code? If so, what is a safe code to send that would be safe to listen for on the client? Maybe I should send a custom header?

0 Answers
Related