Search code examples
gooauthtokenrefresh-token

OAuth token expired and refresh token is not set


I am working on some HTTP APIs for which I need OAuth. I am using OAuth Package. It works at first but after some time I start getting error

Token expired and refresh token is not set.

Here is my config

userCfg := &oauth2.Config{
    ClientID:     a.ClientID,
    ClientSecret: a.ClientSecret,
    Endpoint: oauth2.Endpoint{
        TokenURL:  a.ProviderURL,
        AuthStyle: oauth2.AuthStyleInParams, // basic auth is not supported by Ping
    },
}

Solution

  • I fixed the problem on my own, I put a check that if a received token expires error then instead of sending the error back, I request the token again else I return the error.

    refreshErr := "oauth2: token expired and refresh token is not set"
    
    // use token source to retrieve the configured token or a new token
    token, err := a.tokenSource.Token()
    if err != nil && strings.Contains(err.Error(), refreshErr) {
        // update the token source
        a.tokenSource, err = a.getUserToken()
        if err != nil {
            return "", err
        }
    
        // get the new token
        token, err = a.tokenSource.Token()
        if err != nil {
            return "", err
        }
    } else if err != nil { // some other error than refresh token error
        return "", err
    }
    

    You can define the refreshErr as a constant in your code.