how to use google api library oauth2? I have id token and access token

Viewed 691

How do I authorize access to the backend(with go google libary) given that ive authenticated the user from the front end? Front end Auth, I have access_token or id_token.

  • Is there a way to convert id_token to an access token?
  • Is there a way to use id_token to run calendar.NewService?
  • Is there a way to use access_token to run calendar.NewService?

my setup

In the extension, I done both:

  • From GCP creds oauth2 "chrome app" i can get the "access token".
  • from GCP creds oauth2 "web app", i can get the "id token".

In the backend, using go google api library for calendar

config := &oauth2.Config{...}
// ...
token, err := config.Exchange(ctx, ...)
calendarService, err := calendar.NewService(ctx, option.WithTokenSource(config.TokenSource(ctx, token)))
res, err := calService.Events.List("myemail@gmail.com").Do()

I have no idea how to use my id_token or access_token to use this lib. So far i can do curl requests with the access_token, but that doesnt use this library. is there a way with this google library?

Attempts

  • Ive read in cross identity, that so long as you point to the same client ID in the same project youre good to go. but i keep getting, token expired or not found
  • i hear id_token is just jwt. so i tried, but i cant get the types correct, so cant even run it.
jwt, err := google.JWTConfigFromJSON(g.key, gmail.GmailReadonlyScope)     
jwt.Subject = "myname@gmail.com" //impersonate user   
service, err := calendar.NewService(ctx, option.WithHTTPClient(jwt.Client(ctx)))
  • tried with oauth2 key.json
serviceAccountKey, err := ioutil.ReadFile("oauth2_webapp.json")  
conf, err := google.ConfigFromJSON(serviceAccountKey, calendar.CalendarReadonlyScope) 
token, err := conf.Exchange(ctx,"code") // code seems like another method 
calendarService, err := calendar.NewService(ctx,
option.WithTokenSource(config.TokenSource(ctx, token))) 
res, err := calService.Events.List("myemail@gmail.com").Do()

"code" shouldnt matter, since i do not want to auth the user via browser link. at this point The user should assume already authenticated from front end. but this doesnt work either.

1 Answers

sorry the docs dont have examples. Yeah i tried variations, and finally got it.

id_token is useless.

prior to access token, i had an authCode. I wish in their docs, they said authcode instead of code. i simply passed the auth code from front end to back end. since i am new to this, remove any html encoding. ie(%2f => /). that was also one reason i couldnt get it.

below works:

authCode := "4/3AGEkPVEN9O**70ish char***G0uOPYtQWkUSc" 
// authcode was html encoded which the conf.Exchange needed a decoded version.
saKey, err := ioutil.ReadFile("oauth2_webapp.json")  
conf, err := google.ConfigFromJSON(saKey, calendar.CalendarReadonlyScope) 
token, err := conf.Exchange(ctx,authCode)
Related