diff options
Diffstat (limited to 'backend/internal/auth')
-rw-r--r-- | backend/internal/auth/auth.go | 55 |
1 files changed, 55 insertions, 0 deletions
diff --git a/backend/internal/auth/auth.go b/backend/internal/auth/auth.go new file mode 100644 index 0000000..edad914 --- /dev/null +++ b/backend/internal/auth/auth.go @@ -0,0 +1,55 @@ +package auth + +import ( + "context" + "errors" + + "github.com/ansg191/ibd-trader-backend/internal/config" + + "github.com/coreos/go-oidc/v3/oidc" + "golang.org/x/oauth2" +) + +// Authenticator is used to authenticate our users. +type Authenticator struct { + *oidc.Provider + oauth2.Config +} + +// New instantiates the *Authenticator. +func New(cfg *config.Config) (*Authenticator, error) { + provider, err := oidc.NewProvider( + context.Background(), + "https://"+cfg.Auth.Domain+"/", + ) + if err != nil { + return nil, err + } + + conf := oauth2.Config{ + ClientID: cfg.Auth.ClientID, + ClientSecret: cfg.Auth.ClientSecret, + RedirectURL: cfg.Auth.CallbackURL, + Endpoint: provider.Endpoint(), + Scopes: []string{oidc.ScopeOpenID, "profile", "email"}, + } + + return &Authenticator{ + Provider: provider, + Config: conf, + }, nil +} + +// VerifyIDToken verifies that an *oauth2.Token is a valid *oidc.IDToken. +func (a *Authenticator) VerifyIDToken(ctx context.Context, token *oauth2.Token) (*oidc.IDToken, error) { + rawIDToken, ok := token.Extra("id_token").(string) + if !ok { + return nil, errors.New("no id_token field in oauth2 token") + } + + oidcConfig := &oidc.Config{ + ClientID: a.ClientID, + } + + return a.Verifier(oidcConfig).Verify(ctx, rawIDToken) +} |