Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 885
Sredny M Casanova Avatar asked Nov 29 '22 13:11

Sredny M Casanova


1 Answers

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(oauth2.NoContext, 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(oauth2.NoContext, tokenSource)
resp, err := client.Get(url)
like image 106
hypnoglow Avatar answered Dec 06 '22 10:12

hypnoglow