How to manually authenticate users in laravel passport, using tokens

Am using a custom handler for websocket in laravel

web.php

WebSocketsRouter::webSocket('/app/{appKey}', \App\SocketServer\SocketHandler::class);

This router dose not accept middleware, thats why am trying to send the token from the frontend and get the user by token

SocketHandler.php

<?php

namespace App\SocketServer;
class SocketHandler extends WebSocketHandler
{
    public function onOpen(ConnectionInterface $connection)
    {

            parent::onOpen($connection);
            $guzzleRequest = $connection->httpRequest;
            parse_str($guzzleRequest->getUri()->getQuery(), $getParameters);

            $token = $getParameters['token'] ?? null;
            if (!$token) {
                throw new Exception('Token required', 401);
            }

            // Here am trying to get the user by the token
           $user = //
           Auth::login($user)
    }

 
}

How to authenticate a user inside the SockerHandler class?

thank you

Upvotes: 0

Views: 446

Answers (2)

Stanislav Stankov
Stanislav Stankov

Reputation: 135

In Laravel 11 with Passport I did it as optional Middleware:

namespace App\Domains\Boilerplate\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

final class OptionalAuthMiddleware
{
    public const string ALIAS = 'auth_optional';

    /**
     * Handle an incoming request.
     *
     * @param Request $request
     * @param Closure $next
     *
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $token = $request->bearerToken();

        if ($token) {
            // TODO: Need to check if this is the best way to do the things.
            $passportGuard = Auth::guard('api');
            $authUser = $passportGuard->user();
            if ($authUser) {
                Auth::setUser($passportGuard->user());
            }
        }

        return $next($request);
    }
}

I appeneded to the point:

    Route::get('/imports/{importId}', [ImportController::class, 'get'])
        ->whereUuid('importId')
        ->middleware('auth_optional');

And in boostrap/app, added it as:


    ->withMiddleware(function (Middleware $middleware) {
        // run with every request
        ... other middlewares

        // alias - add all Alias here in same array.
        $middleware->alias([
            OptionalAuthMiddleware::ALIAS => OptionalAuthMiddleware::class,
            ....
    ]);

Upvotes: 0

Othmane Nemli
Othmane Nemli

Reputation: 1193

You have to resolve TokenRepository and get the token


use Laravel\Passport\TokenRepository;
 
$tokenRepository = app(TokenRepository::class);

// this will return instance of \Laravel\Passport\Token
$token = $tokenRepository->find($token); 

if($token){
  $user = $token->user; //User model instance
}

// .....


More details functions:

Upvotes: 0

Related Questions