cauth/auth.go

50 lines
1.1 KiB
Go
Raw Normal View History

2024-10-26 10:27:18 +00:00
package cauth
import (
"context"
"fmt"
"github.com/coreos/go-oidc/v3/oidc"
"golang.org/x/oauth2"
)
type Params struct {
ClientID string
ClientSecret string
RedirectURL string
AWSRegion string
UserPoolID string
}
type Authenticator struct {
Provider *oidc.Provider
OAuth2Config *oauth2.Config
Verifier *oidc.IDTokenVerifier
}
func NewAuthenticator(ctx context.Context, params Params) (*Authenticator, error) {
issuer := fmt.Sprintf("https://cognito-idp.%s.amazonaws.com/%s", params.AWSRegion, params.UserPoolID)
provider, err := oidc.NewProvider(ctx, issuer)
if err != nil {
return nil, fmt.Errorf("failed to get provider: %v", err)
}
oauth2Config := &oauth2.Config{
ClientID: params.ClientID,
ClientSecret: params.ClientSecret,
RedirectURL: params.RedirectURL,
Endpoint: provider.Endpoint(),
Scopes: []string{oidc.ScopeOpenID, "profile", "email"},
}
verifier := provider.Verifier(&oidc.Config{
ClientID: params.ClientID,
})
return &Authenticator{
Provider: provider,
OAuth2Config: oauth2Config,
Verifier: verifier,
}, nil
}