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

dadams97's avatar

Passport + Spotify API

I am currently building an API that requires me to use the PKCE auth flow for connecting to Spotify. I have Laravel passport setup in my project.

I have the following two routes: user authorization and access token request.

/** Spotify API Routes */
Route::get('auth/redirect', function (Request $request) {
    $request->session()->put('state', $state = Str::random(40));

    $request->session()->put(
        'code_verifier',
        $code_verifier = Str::random(128)
    );

    $codeChallenge = strtr(rtrim(
        base64_encode(hash('sha256', $code_verifier, true)),
        '='
    ), '+/', '-_');

    $query = http_build_query([
        'client_id' => env('SPOTIFY_CLIENT_ID'),
        'redirect_uri' => 'http://localhost:8000/auth/access-token',
        'response_type' => 'code',
        'scope' => 'user-read-private user-read-email',
        'state' => $state,
        'code_challenge' => $codeChallenge,
        'code_challenge_method' => 'S256',
    ]);

    return redirect('https://accounts.spotify.com/authorize?' . $query);
})->name('spotify.authorize');

Route::get('auth/access-token', function (Request $request) {
    $state = $request->session()->pull('state');
    $codeVerifier = $request->session()->pull('code_verifier');
 
    throw_unless(
        strlen($state) > 0 && $state === $request->state,
        InvalidArgumentException::class
    );
 
    $response = Http::asForm()->post('https://accounts.spotify.com/api/token', [
        'grant_type' => 'authorization_code',
        'client_id' => env('SPOTIFY_CLIENT_ID'),
        'redirect_uri' => 'http://localhost:8000/auth/access-token',
        'code_verifier' => $codeVerifier,
        'code' => $request->code,
    ]);
 
    return $response->json();

What I am trying to understand is how do I setup my route such that the access tokens are stored for subsequent API requests to Spotify? It is my understanding that Laravel Passport has it's own tables but I am unsure how to store my access tokens in my scenario because I would like to setup events for refresh tokens in the future as well.

I would appreciate the community's help on this. Thank you!

0 likes
3 replies
Arlinewheeler's avatar

Laravel Passport is an OAuth2 server implementation. It allows your Laravel app to issue tokens to clients. But spotify premium apk is an OAuth provider, meaning you are the client, not the server.

So, Laravel Passport is not directly used in your PKCE + Spotify flow. You can still use Passport for your app’s internal authentication, but it doesn't handle external OAuth tokens like Spotify’s.

1 like

Please or to participate in this conversation.