1. Posts/

Laravel Sanctum custom token resolver

·1 min

By default, Laravel Sanctum uses a bearer token to resolve authenticated users.

But there is a way to modify this behavior by providing a custom callback for sanctum.

Here is an example of how it can be retrieved from a query string named api_key with a fallback to a bearer token.

Place this code to AuthServiceProvider::boot method.


namespace App\Providers;

use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Http\Request;
use Laravel\Sanctum\Sanctum;

class AuthServiceProvider extends ServiceProvider
    public function boot()
        // ...

        Sanctum::getAccessTokenFromRequestUsing(function (Request $request) {
            return $request->get('api_key', $request->bearerToken());