Skip to main content

Exchange a Refresh Token for an Access Token

Explanation

Assuming you requested a Refresh Token as part of the Authorization Code exchange, you can then use that Refresh Token to generate new Access Tokens after the original Access Token has expired.

package main

import (
"context"
"log"

"golang.org/x/oauth2"
)

const (
ClientID = "client-id"
ClientSecret = "client-secret"
RedirectUrl = "http://localhost:8080/redirect"

// The Refresh Token should have been retrieved earlier during the
// Authorization Code exchange.
RefreshToken = "refresh-token"
)

func main() {
// First we set up our OAuth2 configuration.
//
// We include the ClientID from our OAuth Client, we
// specify the Authorize and Token URLs, and we set up the redirect URL.
// The values for these fields are set up when you create the OAuth Client
// or are provided in the documentation. The Client Secret is left empty,
// as we are using a public client.
//
// Finally, we specify the Scopes we want to return. The Scopes specified
// here mean we return all permissions available to the user. For more
// information on what this means please view the IMS Permissions and Scopes
// guide.
config := oauth2.Config{
ClientID: ClientID,
ClientSecret: ClientSecret,
Endpoint: oauth2.Endpoint{
AuthURL: "https://platform-auth.improbable.io/auth/v1/authorize",
TokenURL: "https://platform-auth.improbable.io/auth/v1/token",
},
RedirectURL: RedirectUrl,
Scopes: []string{"[*]:*"},
}

// We pass the Refresh Token into a TokenSource object, and then we can
// ask the token source to generate a token for us.
//
// Note, that the Token object created here is the same as the object
// returned directly by the exchange in the Authorization Code examples.
src := config.TokenSource(context.Background(), &oauth2.Token{
RefreshToken: RefreshToken,
})

token, err := src.Token()
if err != nil {
log.Fatalf("could not Refresh Token: %v", err)
}

log.Printf("Access Token: %s", token.AccessToken)
log.Printf("Expires: %s", token.Expiry.String())
}