zitadel-go
zitadel-go copied to clipboard
Allow the client to accept an oauth2.TokenSource
I would like to use the OAuth2 clientcredentials tokensource when using the SDK.
Its working, but it requires that I coerce JWTProfileTokenSource into doing something that it wasn't meant to do.
The library should only take a oauth2.TokenSource, where JWTProfileTokenSource return an oauth2.TokenSouce.
The same would work for a PAT version (i.e. static token).
import (
admin "github.com/zitadel/zitadel-go/v2/pkg/client/admin"
middleware "github.com/zitadel/zitadel-go/v2/pkg/client/middleware"
zitadel "github.com/zitadel/zitadel-go/v2/pkg/client/zitadel"
"golang.org/x/oauth2/clientcredentials"
)
var clientcredentialsConfig *clientcredentials.Config = &clientcredentials.Config{
ClientID: saSystemReaderClientId,
ClientSecret: saSystemReaderClientSecret,
TokenURL: "http://localhost:8081/oauth/v2/token",
Scopes: []string{oidc.ScopeOpenID, zitadel.ScopeZitadelAPI()},
}
func JWTProfileFromClientCredentials(cc *clientcredentials.Config) middleware.JWTProfileTokenSource {
return func(issuer string, scopes []string) (oauth2.TokenSource, error) {
return cc.TokenSource(context.Background()), nil
}
}
....
adminReaderClient, err := admin.NewClient(
*issuer,
*api,
[]string{},
zitadel.WithJWTProfileTokenSource(JWTProfileFromClientCredentials(clientcredentialsConfig)),
zitadel.WithInsecure(),
)
Personal Access Token example
// PATTokenSource ...
type PATTokenSource struct {
PAT string
}
// Duration100Years ...
const Duration100Years = 100 * 365 * 24 * time.Hour
// Token ...
func (s *PATTokenSource) Token() (*oauth2.Token, error) {
return &oauth2.Token{
AccessToken: s.PAT,
TokenType: "Bearer",
Expiry: time.Now().Add(Duration100Years),
}, nil
}
// PATJWTProfileTokenSource ...
func PATJWTProfileTokenSource(pat string) middleware.JWTProfileTokenSource {
return func(issuer string, scopes []string) (oauth2.TokenSource, error) {
return &PATTokenSource{
PAT: pat,
}, nil
}
}
var options []zitadel.Option
options = append(options , zitadel.WithJWTProfileTokenSource(startup.PATJWTProfileTokenSource(ZitadelPersonalAccessToken)))
options = append(options, zitadel.WithInsecure())
Thanks for sharing this.
We will work on our go sdk in the coming sprint and I think this will be a super input.
CC @hifabienne since I am not sure who will work on this I am going to tag you :grin:
I just made a reference in the issue for the go sdk/examples