zitadel-oidc/pkg/oidc/token_request.go
Tim Möhlmann 1165d88c69
feat(op): dynamic issuer depending on request / host (#278)
* feat(op): dynamic issuer depending on request / host

BREAKING CHANGE: The OpenID Provider package is now able to handle multiple issuers with a single storage implementation. The issuer will be selected from the host of the request and passed into the context, where every function can read it from if necessary. This results in some fundamental changes:
 - `Configuration` interface:
   - `Issuer() string` has been changed to `IssuerFromRequest(r *http.Request) string`
   - `Insecure() bool` has been added
 - OpenIDProvider interface and dependants:
   - `Issuer` has been removed from Config struct
   - `NewOpenIDProvider` now takes an additional parameter `issuer` and returns a pointer to the public/default implementation and not an OpenIDProvider interface:
     `NewOpenIDProvider(ctx context.Context, config *Config, storage Storage, opOpts ...Option) (OpenIDProvider, error)` changed to `NewOpenIDProvider(ctx context.Context, issuer string, config *Config, storage Storage, opOpts ...Option) (*Provider, error)`
   - therefore the parameter type Option changed to the public type as well: `Option func(o *Provider) error`
   - `AuthCallbackURL(o OpenIDProvider) func(string) string` has been changed to `AuthCallbackURL(o OpenIDProvider) func(context.Context, string) string`
   - `IDTokenHintVerifier() IDTokenHintVerifier` (Authorizer, OpenIDProvider, SessionEnder interfaces), `AccessTokenVerifier() AccessTokenVerifier` (Introspector, OpenIDProvider, Revoker, UserinfoProvider interfaces) and `JWTProfileVerifier() JWTProfileVerifier` (IntrospectorJWTProfile, JWTAuthorizationGrantExchanger, OpenIDProvider, RevokerJWTProfile interfaces) now take a context.Context parameter `IDTokenHintVerifier(context.Context) IDTokenHintVerifier`, `AccessTokenVerifier(context.Context) AccessTokenVerifier` and `JWTProfileVerifier(context.Context) JWTProfileVerifier`
   - `OidcDevMode` (CAOS_OIDC_DEV) environment variable check has been removed, use `WithAllowInsecure()` Option
 - Signing: the signer is not kept in memory anymore, but created on request from the loaded key:
   - `Signer` interface and func `NewSigner` have been removed
   - `ReadySigner(s Signer) ProbesFn` has been removed
   - `CreateDiscoveryConfig(c Configuration, s Signer) *oidc.DiscoveryConfiguration` has been changed to `CreateDiscoveryConfig(r *http.Request, config Configuration, storage DiscoverStorage) *oidc.DiscoveryConfiguration`
   - `Storage` interface:
     - `GetSigningKey(context.Context, chan<- jose.SigningKey)` has been changed to `SigningKey(context.Context) (SigningKey, error)`
     - `KeySet(context.Context) ([]Key, error)` has been added
     - `GetKeySet(context.Context) (*jose.JSONWebKeySet, error)` has been changed to `KeySet(context.Context) ([]Key, error)`
   - `SigAlgorithms(s Signer) []string` has been changed to `SigAlgorithms(ctx context.Context, storage DiscoverStorage) []string`
   - KeyProvider interface: `GetKeySet(context.Context) (*jose.JSONWebKeySet, error)` has been changed to `KeySet(context.Context) ([]Key, error)`
   - `CreateIDToken`: the Signer parameter has been removed

* move example

* fix examples

* fix mocks

* update readme

* fix examples and update usage

* update go module version to v2

* build branch

* fix(module): rename caos to zitadel

* fix: add state in access token response (implicit flow)

* fix: encode auth response correctly (when using query in redirect uri)

* fix query param handling

* feat: add all optional claims of the introspection response

* fix: use default redirect uri when not passed

* fix: exchange cors library and add `X-Requested-With` to Access-Control-Request-Headers (#261)

* feat(op): add support for client credentials

* fix mocks and test

* feat: allow to specify token type of JWT Profile Grant

* document JWTProfileTokenStorage

* cleanup

* rp: fix integration test

test username needed to be suffixed by issuer domain

* chore(deps): bump golang.org/x/text from 0.5.0 to 0.6.0

Bumps [golang.org/x/text](https://github.com/golang/text) from 0.5.0 to 0.6.0.
- [Release notes](https://github.com/golang/text/releases)
- [Commits](https://github.com/golang/text/compare/v0.5.0...v0.6.0)

---
updated-dependencies:
- dependency-name: golang.org/x/text
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

* op: mock: cleanup commented code

* op: remove duplicate code

code duplication caused by merge conflict selections

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: Livio Amstutz <livio.a@gmail.com>
Co-authored-by: adlerhurst <silvan.reusser@gmail.com>
Co-authored-by: Stefan Benz <46600784+stebenz@users.noreply.github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-02-09 17:10:22 +01:00

223 lines
6.9 KiB
Go

package oidc
import (
"encoding/json"
"fmt"
"time"
"gopkg.in/square/go-jose.v2"
)
const (
// GrantTypeCode defines the grant_type `authorization_code` used for the Token Request in the Authorization Code Flow
GrantTypeCode GrantType = "authorization_code"
// GrantTypeRefreshToken defines the grant_type `refresh_token` used for the Token Request in the Refresh Token Flow
GrantTypeRefreshToken GrantType = "refresh_token"
// GrantTypeClientCredentials defines the grant_type `client_credentials` used for the Token Request in the Client Credentials Token Flow
GrantTypeClientCredentials GrantType = "client_credentials"
// GrantTypeBearer defines the grant_type `urn:ietf:params:oauth:grant-type:jwt-bearer` used for the JWT Authorization Grant
GrantTypeBearer GrantType = "urn:ietf:params:oauth:grant-type:jwt-bearer"
// GrantTypeTokenExchange defines the grant_type `urn:ietf:params:oauth:grant-type:token-exchange` used for the OAuth Token Exchange Grant
GrantTypeTokenExchange GrantType = "urn:ietf:params:oauth:grant-type:token-exchange"
// GrantTypeImplicit defines the grant type `implicit` used for implicit flows that skip the generation and exchange of an Authorization Code
GrantTypeImplicit GrantType = "implicit"
// ClientAssertionTypeJWTAssertion defines the client_assertion_type `urn:ietf:params:oauth:client-assertion-type:jwt-bearer`
// used for the OAuth JWT Profile Client Authentication
ClientAssertionTypeJWTAssertion = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"
)
var AllGrantTypes = []GrantType{
GrantTypeCode, GrantTypeRefreshToken, GrantTypeClientCredentials,
GrantTypeBearer, GrantTypeTokenExchange, GrantTypeImplicit,
ClientAssertionTypeJWTAssertion,
}
type GrantType string
type TokenRequest interface {
// GrantType GrantType `schema:"grant_type"`
GrantType() GrantType
}
type TokenRequestType GrantType
type AccessTokenRequest struct {
Code string `schema:"code"`
RedirectURI string `schema:"redirect_uri"`
ClientID string `schema:"client_id"`
ClientSecret string `schema:"client_secret"`
CodeVerifier string `schema:"code_verifier"`
ClientAssertion string `schema:"client_assertion"`
ClientAssertionType string `schema:"client_assertion_type"`
}
func (a *AccessTokenRequest) GrantType() GrantType {
return GrantTypeCode
}
// SetClientID implements op.AuthenticatedTokenRequest
func (a *AccessTokenRequest) SetClientID(clientID string) {
a.ClientID = clientID
}
// SetClientSecret implements op.AuthenticatedTokenRequest
func (a *AccessTokenRequest) SetClientSecret(clientSecret string) {
a.ClientSecret = clientSecret
}
// RefreshTokenRequest is not useful for making refresh requests because the
// grant_type is not included explicitly but rather implied.
type RefreshTokenRequest struct {
RefreshToken string `schema:"refresh_token"`
Scopes SpaceDelimitedArray `schema:"scope"`
ClientID string `schema:"client_id"`
ClientSecret string `schema:"client_secret"`
ClientAssertion string `schema:"client_assertion"`
ClientAssertionType string `schema:"client_assertion_type"`
}
func (a *RefreshTokenRequest) GrantType() GrantType {
return GrantTypeRefreshToken
}
// SetClientID implements op.AuthenticatedTokenRequest
func (a *RefreshTokenRequest) SetClientID(clientID string) {
a.ClientID = clientID
}
// SetClientSecret implements op.AuthenticatedTokenRequest
func (a *RefreshTokenRequest) SetClientSecret(clientSecret string) {
a.ClientSecret = clientSecret
}
type JWTTokenRequest struct {
Issuer string `json:"iss"`
Subject string `json:"sub"`
Scopes SpaceDelimitedArray `json:"-"`
Audience Audience `json:"aud"`
IssuedAt Time `json:"iat"`
ExpiresAt Time `json:"exp"`
private map[string]interface{}
}
func (j *JWTTokenRequest) MarshalJSON() ([]byte, error) {
type Alias JWTTokenRequest
a := (*Alias)(j)
b, err := json.Marshal(a)
if err != nil {
return nil, err
}
if len(j.private) == 0 {
return b, nil
}
err = json.Unmarshal(b, &j.private)
if err != nil {
return nil, fmt.Errorf("jws: invalid map of custom claims %v", j.private)
}
return json.Marshal(j.private)
}
func (j *JWTTokenRequest) UnmarshalJSON(data []byte) error {
type Alias JWTTokenRequest
a := (*Alias)(j)
err := json.Unmarshal(data, a)
if err != nil {
return err
}
err = json.Unmarshal(data, &j.private)
if err != nil {
return err
}
return nil
}
func (j *JWTTokenRequest) GetCustomClaim(key string) interface{} {
return j.private[key]
}
// GetIssuer implements the Claims interface
func (j *JWTTokenRequest) GetIssuer() string {
return j.Issuer
}
// GetAudience implements the Claims and TokenRequest interfaces
func (j *JWTTokenRequest) GetAudience() []string {
return j.Audience
}
// GetExpiration implements the Claims interface
func (j *JWTTokenRequest) GetExpiration() time.Time {
return time.Time(j.ExpiresAt)
}
// GetIssuedAt implements the Claims interface
func (j *JWTTokenRequest) GetIssuedAt() time.Time {
return time.Time(j.IssuedAt)
}
// GetNonce implements the Claims interface
func (j *JWTTokenRequest) GetNonce() string {
return ""
}
// GetAuthenticationContextClassReference implements the Claims interface
func (j *JWTTokenRequest) GetAuthenticationContextClassReference() string {
return ""
}
// GetAuthTime implements the Claims interface
func (j *JWTTokenRequest) GetAuthTime() time.Time {
return time.Time{}
}
// GetAuthorizedParty implements the Claims interface
func (j *JWTTokenRequest) GetAuthorizedParty() string {
return ""
}
// SetSignatureAlgorithm implements the Claims interface
func (j *JWTTokenRequest) SetSignatureAlgorithm(_ jose.SignatureAlgorithm) {}
// GetSubject implements the TokenRequest interface
func (j *JWTTokenRequest) GetSubject() string {
return j.Subject
}
// GetScopes implements the TokenRequest interface
func (j *JWTTokenRequest) GetScopes() []string {
return j.Scopes
}
type TokenExchangeRequest struct {
subjectToken string `schema:"subject_token"`
subjectTokenType string `schema:"subject_token_type"`
actorToken string `schema:"actor_token"`
actorTokenType string `schema:"actor_token_type"`
resource []string `schema:"resource"`
audience Audience `schema:"audience"`
Scope SpaceDelimitedArray `schema:"scope"`
requestedTokenType string `schema:"requested_token_type"`
}
type ClientCredentialsRequest struct {
GrantType GrantType `schema:"grant_type"`
Scope SpaceDelimitedArray `schema:"scope"`
ClientID string `schema:"client_id"`
ClientSecret string `schema:"client_secret"`
ClientAssertion string `schema:"client_assertion"`
ClientAssertionType string `schema:"client_assertion_type"`
}