Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jonerickson's avatar

Authenticating via session within SPA (JWT)

I have built out a SPA with Vue.js using JWT authentication via jwt-auth. Everything works as it should however I am now trying to incorporate some third party packages such as Laravel Horizon and Vapor UI that use the web auth middleware. Since JWT Auth does not use sessions for authentication, how do I authenticate a user to access some web routes? Below is my auth controller as it stands. I do not want to have two stores that manage auth status such as a session, and the JWT stored in local storage. Any help would be great.

public function login(LoginRequest $request)
{
    // Get the login credentials
    $credentials = request(['email', 'password']);

    // If we are logging in via and Ajax request
    if ($request->expectsJson()) {

    	// Attempt to login
	if ($token = Auth::guard($request->admin ? 'admin' : 'user')->attempt($credentials)) {

		    // If logged in as admin
		    if (Auth::guard('admin')->check()) {

			    // Log the event
			    AdminLogin::broadcast(Auth::guard('admin')->user());
		    }

		    // If logged in as admin
		    if (Auth::guard('user')->check()) {

			    // Log the event
			    UserLogin::broadcast(Auth::guard('user')->user());
		    }

		    // Login was successful
		    return response()->api([
			    'token_type' => 'bearer',
			    'access_token' => $token,
			    'expires_in' => JWTFactory::getTTL() * 60
		    ])->header('Authorization', 'Bearer ' . $token);
	    }
    }

    // Login invalid
    throw ValidationException::withMessages([
	    'email' => 'The username and password do not match.',
    ]);
}
0 likes
1 reply
jonerickson's avatar

Figured out a decent implementation. Created a middleware that uses Auth:once() to log the user in once for a single request and then attached the middleware to any web route that needs authentication. You must pass the token as a Query Parmeter so that the JWT guard can authenticate you, and then log you in. The middleware excepts your auth guards to check the request against. For example, "once:admin".

/**
 * Handle an incoming request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Closure  $next
 * @return mixed
 */
public function handle($request, Closure $next, ...$guards)
{
	// If we some guards
    if (!empty($guards)) {

    	// Loop through the guards
	    foreach ($guards as $guard) {

		    // Log the API user in first to create a web session
		    if (Auth::guard($guard)->check() AND !Auth::guard('web')->check()) {

			    // Create a web session
			    Auth::guard('web')->onceUsingId(Auth::guard($guard)->user()->id);

			    // Get out of loop
			    break;
		    }
	    }
    }

    // Continue on to the next response
    return $next($request);
}

Please or to participate in this conversation.