fostertheweb / spotify-web-sdk

A Typescript SDK for the Spotify Web API with types for returned data.
https://fostertheweb.github.io/spotify-web-sdk/
Other
3 stars 2 forks source link

(Web) Existing expired token deleted when SDK is initialized with PKCE strategy #15

Open SuspiciousLookingOwl opened 9 months ago

SuspiciousLookingOwl commented 9 months ago

Existing expired token seem to be removed from local storage instead of being refreshed when the SDK is being initialized.

To replicate:

  1. Initialize the SDK with PKCE Strategy like usual
    const sdk = SpotifyApi.withUserAuthorization(...);
  2. Authenticate and complete the auth redirection normally
    sdk.authenticate();
  3. Replace the expires value stored on the local storage manually using browser's dev console to simulate the token being expired
    
    // get the token value
    localStorage.getItem("spotify-sdk:AuthorizationCodeWithPKCEStrategy:token"); 
    // { "access_token": "...", "token_type": "Bearer", "expires_in": 3600, "refresh_token": "...", "scope": "...", "expires": 1708419488712 }

// then replace the token value on the local storage so that the token seems expired localStorage.getItem( "spotify-sdk:AuthorizationCodeWithPKCEStrategy:token", '{ "access_token": "...", "token_type": "Bearer", "expires_in": 3600, "refresh_token": "...", "scope": "...", "expires": 1600000000000 }' );

4. Reload the page so that the SDK is re-initialized again.

5. The token is now removed from the local storage instead of being refreshed and user has to reauthenticate again
```ts
// get the token value
localStorage.getItem("spotify-sdk:AuthorizationCodeWithPKCEStrategy:token"); 
// null

I don't know if this is the intended behaviour.

fostertheweb commented 8 months ago

Hello @SuspiciousLookingOwl, sorry for the delay. I have also experienced problems recently with my session not refreshing, so I'm going to take a deeper look. I appreciate you showing me all the steps to reproduce the issue.

SuspiciousLookingOwl commented 8 months ago

I ended up writing my own SDK implementation based on this library, stripping all of the features that I don't need, and fixing this bug for my own app.

If I recall correctly, this part of the code caused the issue, where this.updateFunctions.has(cacheKey) returns false, presumably it not being set with AuthorizationCodeWithPKCEStrategy.cacheKey when the SDK is being initialized, causing it to not refresh the token.

Hopefully that can help you debug the issue.