microsoft-authentication-library-for-go icon indicating copy to clipboard operation
microsoft-authentication-library-for-go copied to clipboard

[Feature Request] Support oauth2.TokenSource

Open onitake opened this issue 3 years ago • 3 comments

Is your feature request related to a problem? Please describe. The extension module golang.org/x/oauth2 is often supported by API client implementations to supply credentials to an API endpoint.

In particular, the Go code generator of openapi-generator supports this.

Describe the solution you'd like It would be very nice if a confidential.Client would implement the oauth2.TokenSource interface, so it can be used to generate tokens on demand. Automatic token refresh on expiry can then be trivially supported by calling oauth2.ReuseTokenSource.

Describe alternatives you've considered It's not difficult to write a TokenSource wrapping a confidential.Client, but something provided by MSAL would be nice.

Example:

type TokenWrapper struct {
	confidential.Client
	Scopes []string
}
func (wrapper *TokenWrapper) Token() (*oauth2.Token, error) {
	// Token() doesn't have a Context argument, sadly...
	result, err := wrapper.Client.AcquireTokenByCredential(context.TODO(), wrapper.Scopes)
	if err != nil {
		return nil, err
	}
	return &oauth2.Token{
		AccessToken: result.AccessToken,
		TokenType: "Bearer",
		Expiry: result.ExpiresOn,
	}, nil
}

Additional context Usage with API clients generated by openapi-generator 5.x:

wrapper := &TokenWrapper{confidentialClient, []string{"myscope"}}
client := myapi.NewAPIClient(myapi.NewConfiguration())
request := client.MyApi.MyActionGet(context.WithValue(context.Background(), myapi.ContextOAuth2, wrapper))
request.Execute()

onitake avatar Nov 19 '21 10:11 onitake

For reference, here's an issue about the missing Context in TokenSource: https://github.com/golang/oauth2/issues/262

onitake avatar Nov 19 '21 12:11 onitake

Hi @onitake, MSAL Go API is usually standard across MSALs. So on first look, this seems a little difficult to add. I'll be able to take a closer look at this next week and update you here.

abhidnya13 avatar Nov 25 '21 01:11 abhidnya13

@abhidnya13 Yes, that's understandable.

In any case, my example wrapper works. If someone else has the same need, perhaps it will help them as well.

onitake avatar Nov 25 '21 10:11 onitake