zitadel / zitadel-go

ZITADEL Go - The official client library of ZITADEL for an easy integration into your Go project.
https://zitadel.com
Apache License 2.0
68 stars 27 forks source link

Allow the client to accept an oauth2.TokenSource #212

Open ghstahl opened 1 year ago

ghstahl commented 1 year ago

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(),
  )
ghstahl commented 1 year ago

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())
fforootd commented 1 year ago

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:

hifabienne commented 1 year ago

I just made a reference in the issue for the go sdk/examples