zmb3 / spotify

A Go wrapper for the Spotify Web API
Apache License 2.0
1.33k stars 284 forks source link

Refreshing token with Client Credentials Flow #201

Closed code-qote closed 1 year ago

code-qote commented 1 year ago

Hello. How can I refresh token with Client Credentials Flow? Here is my code:

config := &clientcredentials.Config{
    ClientID:     clientID,
    ClientSecret: clientSecret,
    TokenURL:     spotifyauth.TokenURL,
}
token, err := config.Token(s.ctx)
token.RefreshToken = refreshToken

if err != nil {
    log.Fatal("FATA: SpotifyEngine:" + err.Error())
}

httpClient := spotifyauth.New().Client(s.ctx, token)
s.client = spotify.New(httpClient)
strideynet commented 1 year ago

Why would you use a refresh token with a Client Credentials flow ? You have all the information necessary to generate a new token at will.

code-qote commented 1 year ago

Should I use token, err := config.Token(s.ctx) to generate a new one?

strideynet commented 1 year ago

yes.

code-qote commented 1 year ago

Thank you very much!

schicho commented 1 year ago

I am unsure on what the solution here is. Could you please elaborate?

Some issues mention the token would automatically update, this says I have to do it manually.

Right now I have the following error: oauth2: token expired and refresh token is not set

I create my client with the example code provided

        config := clientcredentials.Config{
        ClientID:     ClientID,
        ClientSecret: ClientSecret,
        TokenURL:     spotifyauth.TokenURL,
    }

    token, err := config.Token(context.Background())
    if err != nil {
        return nil, err
    }
    httpClient := spotifyauth.New().Client(context.Background(), token)
    client := spotify.New(httpClient)

Am I missing something or what is the best practice to update the token?

code-qote commented 1 year ago

I just create a new token and new Spotify client every 30m. It makes it not to expire. Something like this

func newToken() {
    token, _ := s.config.Token(s.ctx)

    if err != nil {
        return
    }
    token.RefreshToken = refreshToken
    httpClient := spotifyauth.New().Client(ctx, token)
    client = spotify.New(httpClient)
}