coreos / go-oidc

A Go OpenID Connect client.
Apache License 2.0
1.95k stars 394 forks source link

How to use UserInfo? #392

Closed tamis-laan closed 1 year ago

tamis-laan commented 1 year ago

I'm using auth0 to secure my API and I'm writing a authentication middleware for go fiber. I'm trying to hit the /userinfo endpoint, I understand I should use the provider.UserInfo() method which requires a context and a auth2.TokenSource. But In my case I don't have an auth2.TokenSource I just have an access token which I extract from the Authorization header of the request.

Is there some way to construct this token source from the access token?

tamis-laan commented 1 year ago

I tried the following:

// Create an OAuth2 token source with the access token
tokenSource := oauth2.StaticTokenSource(&oauth2.Token{
    AccessToken: access_token,
    Expiry:      token.Expiry,
    TokenType:   "Bearer",
})

//
info, err := provider.UserInfo(context.Background(), tokenSource)

log.Println(err, info)

The access_token is a string. This gives the error: runtime error: invalid memory address or nil pointer dereference

ericchiang commented 1 year ago

Please take a look at https://github.com/coreos/go-oidc/blob/v3/example/userinfo/app.go which has a full example

tamis-laan commented 1 year ago

@ericchiang I have studied the example. But the example uses oauth2 to do the authorization part. It implements the /calback route and exchanges the code for the token:

oauth2Token, err := config.Exchange(ctx, r.URL.Query().Get("code"))

I then turns this into a token source and requests the userinfo:

userInfo, err := provider.UserInfo(ctx, oauth2.StaticTokenSource(oauth2Token))

In my case the client (swagger ui) does the authorization and sends the access token to my API in the Authorization header for each request. The API validates the token and I would also want to access /userinfo from my API. But I only have the access token and not a oauth2 token source as I didn't use the Exchange method. How do I construct the token source from just the access token??