mirror of
https://github.com/hanzo-fi/go-libs.git
synced 2026-10-30 20:53:44 +00:00
28 lines
813 B
Go
28 lines
813 B
Go
package client
|
|
|
|
import (
|
|
"context"
|
|
|
|
"golang.org/x/oauth2"
|
|
|
|
"github.com/hanzo-fi/go-libs/v5/pkg/authn/oidc"
|
|
)
|
|
|
|
type CodeExchangeOpt func() []oauth2.AuthCodeOption
|
|
|
|
// CodeExchange handles the oauth2 code exchange, extracting and validating the id_token
|
|
// returning it parsed together with the oauth2 tokens (access, refresh)
|
|
func CodeExchange[C oidc.IDClaims](ctx context.Context, code string, rp RelyingParty, opts ...CodeExchangeOpt) (tokens *oidc.Tokens[C], err error) {
|
|
ctx = context.WithValue(ctx, oauth2.HTTPClient, rp.HttpClient())
|
|
codeOpts := make([]oauth2.AuthCodeOption, 0)
|
|
for _, opt := range opts {
|
|
codeOpts = append(codeOpts, opt()...)
|
|
}
|
|
|
|
token, err := rp.OAuthConfig().Exchange(ctx, code, codeOpts...)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return verifyTokenResponse[C](ctx, token, rp)
|
|
}
|