microsoft-authentication-library-for-go
microsoft-authentication-library-for-go copied to clipboard
[Feature Request] Support oauth2.TokenSource
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()
For reference, here's an issue about the missing Context in TokenSource: https://github.com/golang/oauth2/issues/262
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 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.