rp

package
v2.12.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 16, 2023 License: Apache-2.0 Imports: 17 Imported by: 19

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrUserInfoSubNotMatching = errors.New("sub from userinfo does not match the sub from the id_token")

Functions

func AuthURL

func AuthURL(state string, rp RelyingParty, opts ...AuthURLOpt) string

AuthURL returns the auth request url (wrapping the oauth2 `AuthCodeURL`)

func AuthURLHandler

func AuthURLHandler(stateFn func() string, rp RelyingParty, urlParam ...URLParamOpt) http.HandlerFunc

AuthURLHandler extends the `AuthURL` method with a http redirect handler including handling setting cookie for secure `state` transfer. Custom paramaters can optionally be set to the redirect URL.

func CodeExchange

func CodeExchange[C oidc.IDClaims](ctx context.Context, code string, rp RelyingParty, opts ...CodeExchangeOpt) (tokens *oidc.Tokens[C], err error)

CodeExchange handles the oauth2 code exchange, extracting and validating the id_token returning it parsed together with the oauth2 tokens (access, refresh)

func CodeExchangeHandler

func CodeExchangeHandler[C oidc.IDClaims](callback CodeExchangeCallback[C], rp RelyingParty, urlParam ...URLParamOpt) http.HandlerFunc

CodeExchangeHandler extends the `CodeExchange` method with a http handler including cookie handling for secure `state` transfer and optional PKCE code verifier checking. Custom paramaters can optionally be set to the token URL.

func DelegationTokenRequest

func DelegationTokenRequest(subjectToken string, opts ...tokenexchange.TokenExchangeOption) *tokenexchange.TokenExchangeRequest

DelegationTokenRequest is an implementation of TokenExchangeRequest it exchanges an "urn:ietf:params:oauth:token-type:access_token" with an optional "urn:ietf:params:oauth:token-type:access_token" actor token for an "urn:ietf:params:oauth:token-type:access_token" delegation token

func DeviceAccessToken

func DeviceAccessToken(ctx context.Context, deviceCode string, interval time.Duration, rp RelyingParty) (resp *oidc.AccessTokenResponse, err error)

DeviceAccessToken attempts to obtain tokens from a Device Authorization, by means of polling as defined in RFC, section 3.3 and 3.4: https://www.rfc-editor.org/rfc/rfc8628#section-3.4

func DeviceAuthorization

func DeviceAuthorization(scopes []string, rp RelyingParty) (*oidc.DeviceAuthorizationResponse, error)

DeviceAuthorization starts a new Device Authorization flow as defined in RFC 8628, section 3.1 and 3.2: https://www.rfc-editor.org/rfc/rfc8628#section-3.1

func EndSession

func EndSession(rp RelyingParty, idToken, optionalRedirectURI, optionalState string) (*url.URL, error)

func GenerateAndStoreCodeChallenge

func GenerateAndStoreCodeChallenge(w http.ResponseWriter, rp RelyingParty) (string, error)

GenerateAndStoreCodeChallenge generates a PKCE code challenge and stores its verifier into a secure cookie

func NewRemoteKeySet

func NewRemoteKeySet(client *http.Client, jwksURL string, opts ...func(*remoteKeySet)) oidc.KeySet

func RefreshAccessToken

func RefreshAccessToken(rp RelyingParty, refreshToken, clientAssertion, clientAssertionType string) (*oauth2.Token, error)

RefreshAccessToken performs a token refresh. If it doesn't error, it will always provide a new AccessToken. It may provide a new RefreshToken, and if it does, then the old one should be considered invalid. It may also provide a new IDToken. The new IDToken can be retrieved with token.Extra("id_token").

func RevokeToken

func RevokeToken(rp RelyingParty, token string, tokenTypeHint string) error

RevokeToken requires a RelyingParty that is also a client.RevokeCaller. The RelyingParty returned by NewRelyingPartyOIDC() meets that criteria, but the one returned by NewRelyingPartyOAuth() does not.

tokenTypeHint should be either "id_token" or "refresh_token".

func SkipRemoteCheck

func SkipRemoteCheck() func(set *remoteKeySet)

SkipRemoteCheck will suppress checking for new remote keys if signature validation fails with cached keys and no kid header is set in the JWT

this might be handy to save some unnecessary round trips in cases where the JWT does not contain a kid header and there is only a single remote key please notice that remote keys will then only be fetched if cached keys are empty

func Userinfo

func Userinfo(token, tokenType, subject string, rp RelyingParty) (*oidc.UserInfo, error)

Userinfo will call the OIDC Userinfo Endpoint with the provided token

func VerifyAccessToken

func VerifyAccessToken(accessToken, atHash string, sigAlgorithm jose.SignatureAlgorithm) error

VerifyAccessToken validates the access token according to https://openid.net/specs/openid-connect-core-1_0.html#CodeFlowTokenValidation

func VerifyIDToken

func VerifyIDToken[C oidc.Claims](ctx context.Context, token string, v IDTokenVerifier) (claims C, err error)

VerifyIDToken validates the id token according to https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation

func VerifyTokens

func VerifyTokens[C oidc.IDClaims](ctx context.Context, accessToken, idToken string, v IDTokenVerifier) (claims C, err error)

VerifyTokens implement the Token Response Validation as defined in OIDC specification https://openid.net/specs/openid-connect-core-1_0.html#TokenResponseValidation

Example (CustomClaims)
package main

import (
	"context"
	"fmt"

	tu "github.com/zitadel/oidc/v2/internal/testutil"
	"github.com/zitadel/oidc/v2/pkg/client/rp"
	"github.com/zitadel/oidc/v2/pkg/oidc"
)

// MyCustomClaims extends the TokenClaims base,
// so it implmeents the oidc.Claims interface.
// Instead of carrying a map, we add needed fields// to the struct for type safe access.
type MyCustomClaims struct {
	oidc.TokenClaims
	NotBefore       oidc.Time `json:"nbf,omitempty"`
	AccessTokenHash string    `json:"at_hash,omitempty"`
	Foo             string    `json:"foo,omitempty"`
	Bar             *Nested   `json:"bar,omitempty"`
}

// GetAccessTokenHash is required to implement
// the oidc.IDClaims interface.
func (c *MyCustomClaims) GetAccessTokenHash() string {
	return c.AccessTokenHash
}

// Nested struct types are also possible.
type Nested struct {
	Count int      `json:"count,omitempty"`
	Tags  []string `json:"tags,omitempty"`
}

/*
idToken carries the following claims. foo and bar are custom claims

	{
		"acr": "something",
		"amr": [
			"foo",
			"bar"
		],
		"at_hash": "2dzbm_vIxy-7eRtqUIGPPw",
		"aud": [
			"unit",
			"test",
			"555666"
		],
		"auth_time": 1678100961,
		"azp": "555666",
		"bar": {
			"count": 22,
			"tags": [
				"some",
				"tags"
			]
		},
		"client_id": "555666",
		"exp": 4802238682,
		"foo": "Hello, World!",
		"iat": 1678101021,
		"iss": "local.com",
		"jti": "9876",
		"nbf": 1678101021,
		"nonce": "12345",
		"sub": "tim@local.com"
	}
*/
const idToken = `eyJhbGciOiJSUzI1NiIsImtpZCI6IjEifQ.eyJhY3IiOiJzb21ldGhpbmciLCJhbXIiOlsiZm9vIiwiYmFyIl0sImF0X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dUbW4vGdSmEeJQ3ouhaX0bcW9rdFFLgBI4K2FWJhNivq8JDmCGSxwLu3mI680GWmDaEoAx1M5sCO9lqfIZHGZh-lfAXk27e6FPLlkTDBq8Bx4o4DJ9Fw0hRJGjUTjnYv5cq1vo2-UqldasL6CwTbkzNC_4oQFfRtuodC4Ql7dZ1HRv5LXuYx7KPkOssLZtV9cwtJp5nFzKjcf2zEE_tlbjcpynMwypornRUp1EhCWKRUGkJhJeiP71ECY5pQhShfjBu9Nc5wDpSnZmnk2S4YsPrRK3QkE-iEkas8BfsOCrGoErHjEJexAIDjasGO5PFLWfCA`

func main() {
	v := rp.NewIDTokenVerifier("local.com", "555666", tu.KeySet{},
		rp.WithNonce(func(ctx context.Context) string { return "12345" }),
	)

	// VerifyAccessToken can be called with the *MyCustomClaims.
	claims, err := rp.VerifyTokens[*MyCustomClaims](context.TODO(), accessToken, idToken, v)
	if err != nil {
		panic(err)
	}
	// Here we have typesafe access to the custom claims
	fmt.Println(claims.Foo, claims.Bar.Count, claims.Bar.Tags)
}
Output:

Hello, World! 22 [some tags]

func WithIssuedAtMaxAge

func WithIssuedAtMaxAge(maxAge time.Duration) func(*idTokenVerifier)

WithIssuedAtMaxAge provides the ability to define the maximum duration between iat and now

func WithIssuedAtOffset

func WithIssuedAtOffset(offset time.Duration) func(*idTokenVerifier)

WithIssuedAtOffset mitigates the risk of iat to be in the future because of clock skews with the ability to add an offset to the current time

Types

type AuthURLOpt

type AuthURLOpt func() []oauth2.AuthCodeOption

func WithCodeChallenge

func WithCodeChallenge(codeChallenge string) AuthURLOpt

WithCodeChallenge sets the `code_challenge` params in the auth request

func WithPrompt

func WithPrompt(prompt ...string) AuthURLOpt

WithPrompt sets the `prompt` params in the auth request

type CodeExchangeCallback

type CodeExchangeCallback[C oidc.IDClaims] func(w http.ResponseWriter, r *http.Request, tokens *oidc.Tokens[C], state string, rp RelyingParty)

func UserinfoCallback

UserinfoCallback wraps the callback function of the CodeExchangeHandler and calls the userinfo endpoint with the access token on success it will pass the userinfo into its callback function as well

type CodeExchangeOpt

type CodeExchangeOpt func() []oauth2.AuthCodeOption

func WithClientAssertionJWT

func WithClientAssertionJWT(clientAssertion string) CodeExchangeOpt

WithClientAssertionJWT sets the `client_assertion` param in the token request

func WithCodeVerifier

func WithCodeVerifier(codeVerifier string) CodeExchangeOpt

WithCodeVerifier sets the `code_verifier` param in the token request

type CodeExchangeUserinfoCallback

type CodeExchangeUserinfoCallback[C oidc.IDClaims] func(w http.ResponseWriter, r *http.Request, tokens *oidc.Tokens[C], state string, provider RelyingParty, info *oidc.UserInfo)

type DelegationTokenExchangeRP

type DelegationTokenExchangeRP interface {
	TokenExchangeRP

	// DelegationTokenExchange implement the `Token Exchange Grant`
	// providing an access token in request for a `delegation` token for a given resource / audience
	DelegationTokenExchange(context.Context, string, ...tokenexchange.TokenExchangeOption) (*oauth2.Token, error)
}

DelegationTokenExchangeRP extends the `TokenExchangeRP` interface for the specific `delegation token` request

type Endpoints

type Endpoints struct {
	oauth2.Endpoint
	IntrospectURL          string
	UserinfoURL            string
	JKWsURL                string
	EndSessionURL          string
	RevokeURL              string
	DeviceAuthorizationURL string
}

func Discover

func Discover(issuer string, httpClient *http.Client) (Endpoints, error)

Discover calls the discovery endpoint of the provided issuer and returns the found endpoints

deprecated: use client.Discover

func GetEndpoints

func GetEndpoints(discoveryConfig *oidc.DiscoveryConfiguration) Endpoints

type ErrorHandler

type ErrorHandler func(w http.ResponseWriter, r *http.Request, errorType string, errorDesc string, state string)
var DefaultErrorHandler ErrorHandler = func(w http.ResponseWriter, r *http.Request, errorType string, errorDesc string, state string) {
	http.Error(w, errorType+": "+errorDesc, http.StatusInternalServerError)
}

type IDTokenVerifier

type IDTokenVerifier interface {
	oidc.Verifier
	ClientID() string
	SupportedSignAlgs() []string
	KeySet() oidc.KeySet
	Nonce(context.Context) string
	ACR() oidc.ACRVerifier
	MaxAge() time.Duration
}

func NewIDTokenVerifier

func NewIDTokenVerifier(issuer, clientID string, keySet oidc.KeySet, options ...VerifierOption) IDTokenVerifier

NewIDTokenVerifier returns an implementation of `IDTokenVerifier` for `VerifyTokens` and `VerifyIDToken`

type Option

type Option func(*relyingParty) error

Option is the type for providing dynamic options to the relyingParty

func WithClientKey

func WithClientKey(path string) Option

WithClientKey specifies the path to the key.json to be used for the JWT Profile Client Authentication on the token endpoint

deprecated: use WithJWTProfile(SignerFromKeyPath(path)) instead

func WithCookieHandler

func WithCookieHandler(cookieHandler *httphelper.CookieHandler) Option

WithCookieHandler set a `CookieHandler` for securing the various redirects

func WithCustomDiscoveryUrl

func WithCustomDiscoveryUrl(url string) Option

func WithErrorHandler

func WithErrorHandler(errorHandler ErrorHandler) Option

func WithHTTPClient

func WithHTTPClient(client *http.Client) Option

WithHTTPClient provides the ability to set an http client to be used for the relaying party and verifier

func WithJWTProfile

func WithJWTProfile(signerFromKey SignerFromKey) Option

WithJWTProfile creates a signer used for the JWT Profile Client Authentication on the token endpoint When creating the signer, be sure to include the KeyID in the SigningKey. See client.NewSignerFromPrivateKeyByte for an example.

func WithPKCE

func WithPKCE(cookieHandler *httphelper.CookieHandler) Option

WithPKCE sets the RP to use PKCE (oauth2 code challenge) it also sets a `CookieHandler` for securing the various redirects and exchanging the code challenge

func WithVerifierOpts

func WithVerifierOpts(opts ...VerifierOption) Option

type OptionFunc

type OptionFunc func(RelyingParty)

type RefreshTokenRequest

type RefreshTokenRequest struct {
	RefreshToken        string                   `schema:"refresh_token"`
	Scopes              oidc.SpaceDelimitedArray `schema:"scope"`
	ClientID            string                   `schema:"client_id"`
	ClientSecret        string                   `schema:"client_secret"`
	ClientAssertion     string                   `schema:"client_assertion"`
	ClientAssertionType string                   `schema:"client_assertion_type"`
	GrantType           oidc.GrantType           `schema:"grant_type"`
}

type RelyingParty

type RelyingParty interface {
	// OAuthConfig returns the oauth2 Config
	OAuthConfig() *oauth2.Config

	// Issuer returns the issuer of the oidc config
	Issuer() string

	// IsPKCE returns if authorization is done using `Authorization Code Flow with Proof Key for Code Exchange (PKCE)`
	IsPKCE() bool

	// CookieHandler returns a http cookie handler used for various state transfer cookies
	CookieHandler() *httphelper.CookieHandler

	// HttpClient returns a http client used for calls to the openid provider, e.g. calling token endpoint
	HttpClient() *http.Client

	// IsOAuth2Only specifies whether relaying party handles only oauth2 or oidc calls
	IsOAuth2Only() bool

	// Signer is used if the relaying party uses the JWT Profile
	Signer() jose.Signer

	// GetEndSessionEndpoint returns the endpoint to sign out on a IDP
	GetEndSessionEndpoint() string

	// GetRevokeEndpoint returns the endpoint to revoke a specific token
	GetRevokeEndpoint() string

	// UserinfoEndpoint returns the userinfo
	UserinfoEndpoint() string

	// GetDeviceAuthorizationEndpoint returns the enpoint which can
	// be used to start a DeviceAuthorization flow.
	GetDeviceAuthorizationEndpoint() string

	// IDTokenVerifier returns the verifier interface used for oidc id_token verification
	IDTokenVerifier() IDTokenVerifier

	ErrorHandler() func(http.ResponseWriter, *http.Request, string, string, string)
}

RelyingParty declares the minimal interface for oidc clients

func NewRelyingPartyOAuth

func NewRelyingPartyOAuth(config *oauth2.Config, options ...Option) (RelyingParty, error)

NewRelyingPartyOAuth creates an (OAuth2) RelyingParty with the given OAuth2 Config and possible configOptions it will use the AuthURL and TokenURL set in config

func NewRelyingPartyOIDC

func NewRelyingPartyOIDC(issuer, clientID, clientSecret, redirectURI string, scopes []string, options ...Option) (RelyingParty, error)

NewRelyingPartyOIDC creates an (OIDC) RelyingParty with the given issuer, clientID, clientSecret, redirectURI, scopes and possible configOptions it will run discovery on the provided issuer and use the found endpoints

type SignerFromKey

type SignerFromKey func() (jose.Signer, error)

func SignerFromKeyAndKeyID

func SignerFromKeyAndKeyID(key []byte, keyID string) SignerFromKey

func SignerFromKeyFile

func SignerFromKeyFile(fileData []byte) SignerFromKey

func SignerFromKeyPath

func SignerFromKeyPath(path string) SignerFromKey

type TokenExchangeRP

type TokenExchangeRP interface {
	RelyingParty

	// TokenExchange implement the `Token Exchange Grant` exchanging some token for an other
	TokenExchange(context.Context, *tokenexchange.TokenExchangeRequest) (*oauth2.Token, error)
}

TokenExchangeRP extends the `RelyingParty` interface for the *draft* oauth2 `Token Exchange`

type URLParamOpt

type URLParamOpt func() []oauth2.AuthCodeOption

func WithPromptURLParam

func WithPromptURLParam(prompt ...string) URLParamOpt

WithPromptURLParam sets the `prompt` parameter in a URL.

func WithResponseModeURLParam added in v2.6.0

func WithResponseModeURLParam(mode oidc.ResponseMode) URLParamOpt

WithResponseModeURLParam sets the `response_mode` parameter in a URL.

func WithURLParam

func WithURLParam(key, value string) URLParamOpt

WithURLParam allows setting custom key-vale pairs to an OAuth2 URL.

type VerifierOption

type VerifierOption func(*idTokenVerifier)

VerifierOption is the type for providing dynamic options to the IDTokenVerifier

func WithACRVerifier

func WithACRVerifier(verifier oidc.ACRVerifier) VerifierOption

WithACRVerifier sets the verifier for the acr claim

func WithAuthTimeMaxAge

func WithAuthTimeMaxAge(maxAge time.Duration) VerifierOption

WithAuthTimeMaxAge provides the ability to define the maximum duration between auth_time and now

func WithNonce

func WithNonce(nonce func(context.Context) string) VerifierOption

WithNonce sets the function to check the nonce

func WithSupportedSigningAlgorithms

func WithSupportedSigningAlgorithms(algs ...string) VerifierOption

WithSupportedSigningAlgorithms overwrites the default RS256 signing algorithm

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL