Skip to main content

Exchange an Authorization Code for an Access Token and a Refresh Token

Explanation

The following code sample exchanges an Authorization Code for an Access Token and a Refresh Token. The only change is including generate_refresh_token=true as a query parameter in the exchange request.

package main

import (
"context"
"log"

"golang.org/x/oauth2"
)

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

// The Authorization Code should have already been retrieved from the IMS
// Platform Auth service. See the "Generating an Authorization Code" code
// sample on how to get an AuthorizationCode.
AuthorizationCode = "authorization-code"
)

func main() {
// First we set up our OAuth2 configuration.
//
// We include the ClientID and ClientSecret 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.
//
// 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{"[*]:*"},
}

token, err := config.Exchange(
context.Background(),
AuthorizationCode,
oauth2.SetAuthURLParam("generate_refresh_token", "true"))
if err != nil {
log.Fatalf("could not exchange Authorization Code: %v", err)
}

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