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

RobMeijeren's avatar

validate access token from controller

Hello All,

I had a question about validating access tokens. I have setup Passport with Laravel 5.3 as in the documents and I have a angularjs front end that is placed in the resources folder. To issue access tokens I use the default Laravel Password Grant Client.

This works all fine and I get an access token and refresh token in my angular app with the expiration time. However when I try to access any of my api calls I don't have to authenticate while I explicitly have the auth middleware on the route through a route grouping.

Is there a route coming with Passport which I can call from the function that is being executed with the route call to validate the access token? e.g. oauth/token/validate?

I have searching google for a week now but I can't find anything on this.

Regards,

Rob

angular service calling the validate route

function($resource, $localStorage) {
        return $resource('/api/user', {}, {
            validate: {
                method: 'POST',
                url: '/api/user/validate',
                headers: { 
                    'Accept': 'application/json',
                    'Authorization': 'Bearer ' + $localStorage.access_token
                }
            }
        });
    }

api.php

Route::group(['middleware' => ['api']], function () {
    Route::group(['prefix' => 'user'], function () {
        Route::post('validate', 'LogController@validateToken');
    });
});

validate function

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\User;
use App\Token;
use Hash;
use Auth;
use DateTime;

class LogController extends Controller {

    public function validateToken(Request $request) {
        // here I want to validate the request that is in $request
    }
}
0 likes
4 replies
RobMeijeren's avatar

For those with a similar question:

After searching a lot in the laravel passport code I found and adapted the TokenGuard to get the token from the database and check if it is expired. Find below the code for logging in and validating the access token

<?php

namespace App\Http\Controllers;

use Hash;
use Auth;
use DateTime;
use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Laravel\Passport\TokenRepository;
use League\OAuth2\Server\ResourceServer;
use League\OAuth2\Server\Exception\OAuthServerException;
use Symfony\Bridge\PsrHttpMessage\Factory\DiactorosFactory;

class LogController extends Controller {

    protected $server;
    protected $tokens;

    public function __construct(ResourceServer $server, TokenRepository $tokens) {
        $this->server = $server;
        $this->tokens = $tokens;
    }

    public function login(Request $request){
        $rules = array(
                'username'=>'required|email',
                'password'=>'required|alpha_dash',
        );
    
        $this->validate($request, $rules);

        if(Auth::attempt(array('email' => $request->username, 'password' => $request->password), true)){
            $access_token = Auth::user()->createToken('Access Token')->accessToken;
            
            return json_encode(array('access_token' => $access_token));
        }
        else{
            return json_encode(array('login_error' => 'Deze combinatie van gebruikersnaam en wachtwoord bestaat niet.'));
        }
    }

    public function validateToken(Request $request, $localCall = false) {
         // First, we will convert the Symfony request to a PSR-7 implementation which will
        // be compatible with the base OAuth2 library. The Symfony bridge can perform a
        // conversion for us to a Zend Diactoros implementation of the PSR-7 request.
        $psr = (new DiactorosFactory)->createRequest($request);

        try {
            $psr = $this->server->validateAuthenticatedRequest($psr);

            // Next, we will assign a token instance to this user which the developers may use
            // to determine if the token has a given scope, etc. This will be useful during
            // authorization such as within the developer's Laravel model policy classes.
            $token = $this->tokens->find(
                $psr->getAttribute('oauth_access_token_id')
            );

            $currentDate = new DateTime();
            $tokenExpireDate = new DateTime($token->expires_at);

            $isAuthenticated = $tokenExpireDate > $currentDate ? true : false;

            if($localCall) {
                return $isAuthenticated;
            }
            else {
                return json_encode(array('authenticated' => $isAuthenticated));
            }
        } catch (OAuthServerException $e) {
            if($localCall) {
                return false;
            }
            else {
                return json_encode(array('error' => 'Something went wrong with authenticating. Please logout and login again.'));
            }
        }
    }
}
spawnia's avatar

This is actually super simple to do now. Just recently a bug has been fixed which prevented a correct error response on API calls, now you can just do this:

Route::get('/validate-token', function () {
    return ['data' => 'Token is valid'];
})->middleware('auth:api');

If you are calling this route via ajax or with Accept: application/json header, this will return JSON response. The success response is what is defined in the callback, it could be anything.

In case the authentication through the middleware fails, the response looks like this:

{
    "error": "Unauthenticated."
}
5 likes

Please or to participate in this conversation.