3
votes

I want to validate a token using Laravel Passport. My API's consumer will pass the token via the Authorization header as a Bearer token and I want that Laravel Passport returns me if is a valid token.

I don't want to use a middleware, my API will be in another Laravel Project, but I want this project to call the Laravel Passport server just for check if a token is valid, how can I check the token?

I'm issuing the tokens right, just left verify them, but I don't know how:(

3

3 Answers

4
votes

This is how you can verify tokens without the middleware:

Auth::guard('api')->check();
3
votes

You can create your own middleware. Inside that middleware's handle, pick the Bearer token and call your Passport server, depending on the response returned call next if true, or abort if false. Something like this:

public function handle($request, Closure $next)
{
    try {
        $passportEndpoint = 'your_passport_endpoint_here';
        $client = Http::withHeaders([
            'Content-Type' => 'application/json',
            'Accept' => 'application/json',
            'Authorization' => $request->header('Authorization')
        ]);

        $response = $client->get($passportEndpoint);
        if ($response->status() === 200) {
            $body = $response->object();
            //do some stuff with response here, like setting the global logged in user
            

            return $next($request);
        }
    }
    catch (RequestException $exception) {

    }

    return abort(401, 'You are not authenticated to this service');
}
2
votes

If you don't want to use the Passport middleware in the project where you want to validate the tokens, you would have to create an endpoint in the Laravel Passport server that can accept the token, perform the usual Passport validation and return a response to your service.

It would be an implementation of the Token Introspection spec: https://www.rfc-editor.org/rfc/rfc7662 - though you have to implement it yourself, as I think that Laravel Passport doesn't support it out-of-the-box.

Also, when verifying JSON Web Tokens (if this is the type of tokens that you use), remember that verifying the signature is not enough. Have a look at this best practices article to know how to properly work with JWTs.