Search code examples
gooauth-2.0oauth2client

Renew Access Token using Golang Oauth2 library


I am working in a Golang application, this one is connected to a Oauth2 service, right now I have the refresh token and I need to get a new access token with it, I am using golang.org/x/oauth2 but it wans't successful, so there's something that I am missing, currently I have:

refresh_token := "some_refresh_token"

    var conf = oauth2.Config{
             ClientID:MY_CLIENT,
             ClientSecret:MY_CLIENT_SECRET,
             Scopes:[]string{"refresh_token"},
             RedirectURL:"https://mydomain/callback",
             Endpoint: oauth2.Endpoint{
                AuthURL:"myoauth2Cluster.com/oauth2/auth",
                TokenURL: "myoauth2Cluster.com/oauth2/token",
             },
    }

    t := new (oauth2.Token)
    t.RefreshToken=refresh_token

    myclient := conf.Client(context.Background(),t)

    req, err := http.NewRequest("GET",DontKnowWhichURLhere , nil)

    if err != nil {
        fmt.Println("error:",err.Error())
    }

    mrr, er := myclient.Do(req)

    if(er!=nil){
        fmt.Println(er.Error())
    }else{
        fmt.Println("status code:",mrr.StatusCode)
    }

But I am getting a 404 status, I checked the logs of the Oauth2 server and there I have

msg="completed handling request" measure#https://myOauth2Cluster.latency=100648 method=GET remote=xxx.xxx.xx.xxx request="/" status=404 text_status="Not Found" took=100.648µs

Also, I am not really sure which URL should I stablish when I create the http.NewRequest should it be a callback? or the url of the Oauth2 Server?

If there's some example of how to renew the access token using this library would be nice, but at the moment I haven't found it


Solution

  • Normally you just use your old token and it is refreshed by the oauth2 library implicitly.

    Example:

    In the code below conf is *oauth2.Config.

    Say I'm exchanging the code for the token (first-time auth):

    token, err := conf.Exchange(ctx, code)
    if err != nil {
        log.Fatalln(err)
    }
    
    SaveToken(token)
    

    Now I have my token and I can use it to make requests.

    Later, before I use my token, I let oauth2 automatically refresh it if need:

    tokenSource := conf.TokenSource(context.TODO(), token)
    newToken, err := tokenSource.Token()
    if err != nil {
        log.Fatalln(err)
    }
    
    if newToken.AccessToken != token.AccessToken {
        SaveToken(newToken)
        log.Println("Saved new token:", newToken.AccessToken)
    }
    
    client := oauth2.NewClient(context.TODO(), tokenSource)
    resp, err := client.Get(url)