feat(op): add support for client credentials

This commit is contained in:
Livio Spring 2023-01-30 10:54:22 +01:00
parent 2574ebc6e7
commit 90b99d4d2b
No known key found for this signature in database
GPG key ID: 26BB1C2FA5952CF0
8 changed files with 145 additions and 2 deletions

View file

@ -14,7 +14,7 @@ type clientCredentialsGrant struct {
} }
//ClientCredentialsGrantBasic creates an oauth2 `Client Credentials` Grant //ClientCredentialsGrantBasic creates an oauth2 `Client Credentials` Grant
//sneding client_id and client_secret as basic auth header //sending client_id and client_secret as basic auth header
func ClientCredentialsGrantBasic(scopes ...string) *clientCredentialsGrantBasic { func ClientCredentialsGrantBasic(scopes ...string) *clientCredentialsGrantBasic {
return &clientCredentialsGrantBasic{ return &clientCredentialsGrantBasic{
grantType: "client_credentials", grantType: "client_credentials",
@ -23,7 +23,7 @@ func ClientCredentialsGrantBasic(scopes ...string) *clientCredentialsGrantBasic
} }
//ClientCredentialsGrantValues creates an oauth2 `Client Credentials` Grant //ClientCredentialsGrantValues creates an oauth2 `Client Credentials` Grant
//sneding client_id and client_secret as form values //sending client_id and client_secret as form values
func ClientCredentialsGrantValues(clientID, clientSecret string, scopes ...string) *clientCredentialsGrant { func ClientCredentialsGrantValues(clientID, clientSecret string, scopes ...string) *clientCredentialsGrant {
return &clientCredentialsGrant{ return &clientCredentialsGrant{
clientCredentialsGrantBasic: ClientCredentialsGrantBasic(scopes...), clientCredentialsGrantBasic: ClientCredentialsGrantBasic(scopes...),

View file

@ -15,6 +15,9 @@ const (
//GrantTypeRefreshToken defines the grant_type `refresh_token` used for the Token Request in the Refresh Token Flow //GrantTypeRefreshToken defines the grant_type `refresh_token` used for the Token Request in the Refresh Token Flow
GrantTypeRefreshToken GrantType = "refresh_token" 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 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" GrantTypeBearer GrantType = "urn:ietf:params:oauth:grant-type:jwt-bearer"
@ -198,3 +201,12 @@ type TokenExchangeRequest struct {
Scope SpaceDelimitedArray `schema:"scope"` Scope SpaceDelimitedArray `schema:"scope"`
requestedTokenType string `schema:"requested_token_type"` 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"`
}

View file

@ -35,6 +35,7 @@ type Configuration interface {
GrantTypeRefreshTokenSupported() bool GrantTypeRefreshTokenSupported() bool
GrantTypeTokenExchangeSupported() bool GrantTypeTokenExchangeSupported() bool
GrantTypeJWTAuthorizationSupported() bool GrantTypeJWTAuthorizationSupported() bool
GrantTypeClientCredentialsSupported() bool
IntrospectionAuthMethodPrivateKeyJWTSupported() bool IntrospectionAuthMethodPrivateKeyJWTSupported() bool
IntrospectionEndpointSigningAlgorithmsSupported() []string IntrospectionEndpointSigningAlgorithmsSupported() []string
RevocationAuthMethodPrivateKeyJWTSupported() bool RevocationAuthMethodPrivateKeyJWTSupported() bool

View file

@ -83,6 +83,9 @@ func GrantTypes(c Configuration) []oidc.GrantType {
if c.GrantTypeRefreshTokenSupported() { if c.GrantTypeRefreshTokenSupported() {
grantTypes = append(grantTypes, oidc.GrantTypeRefreshToken) grantTypes = append(grantTypes, oidc.GrantTypeRefreshToken)
} }
if c.GrantTypeClientCredentialsSupported() {
grantTypes = append(grantTypes, oidc.GrantTypeClientCredentials)
}
if c.GrantTypeTokenExchangeSupported() { if c.GrantTypeTokenExchangeSupported() {
grantTypes = append(grantTypes, oidc.GrantTypeTokenExchange) grantTypes = append(grantTypes, oidc.GrantTypeTokenExchange)
} }

View file

@ -256,6 +256,11 @@ func (o *Provider) IntrospectionEndpointSigningAlgorithmsSupported() []string {
return []string{"RS256"} return []string{"RS256"}
} }
func (o *Provider) GrantTypeClientCredentialsSupported() bool {
_, ok := o.storage.(ClientCredentialsStorage)
return ok
}
func (o *Provider) RevocationAuthMethodPrivateKeyJWTSupported() bool { func (o *Provider) RevocationAuthMethodPrivateKeyJWTSupported() bool {
return true return true
} }

View file

@ -28,6 +28,11 @@ type AuthStorage interface {
KeySet(context.Context) ([]Key, error) KeySet(context.Context) ([]Key, error)
} }
type ClientCredentialsStorage interface {
ClientCredentials(ctx context.Context, clientID, clientSecret string) (Client, error)
ClientCredentialsTokenRequest(ctx context.Context, clientID string, scopes []string) (TokenRequest, error)
}
type OPStorage interface { type OPStorage interface {
GetClientByClientID(ctx context.Context, clientID string) (Client, error) GetClientByClientID(ctx context.Context, clientID string) (Client, error)
AuthorizeClientIDSecret(ctx context.Context, clientID, clientSecret string) error AuthorizeClientIDSecret(ctx context.Context, clientID, clientSecret string) error

View file

@ -0,0 +1,111 @@
package op
import (
"context"
"net/http"
"net/url"
httphelper "github.com/zitadel/oidc/v2/pkg/http"
"github.com/zitadel/oidc/v2/pkg/oidc"
)
// ClientCredentialsExchange handles the OAuth 2.0 client_credentials grant, including
// parsing, validating, authorizing the client and finally returning a token
func ClientCredentialsExchange(w http.ResponseWriter, r *http.Request, exchanger Exchanger) {
request, err := ParseClientCredentialsRequest(r, exchanger.Decoder())
if err != nil {
RequestError(w, r, err)
}
validatedRequest, client, err := ValidateClientCredentialsRequest(r.Context(), request, exchanger)
if err != nil {
RequestError(w, r, err)
return
}
resp, err := CreateClientCredentialsTokenResponse(r.Context(), validatedRequest, exchanger, client)
if err != nil {
RequestError(w, r, err)
return
}
httphelper.MarshalJSON(w, resp)
}
// ParseClientCredentialsRequest parsed the http request into a oidc.ClientCredentialsRequest
func ParseClientCredentialsRequest(r *http.Request, decoder httphelper.Decoder) (*oidc.ClientCredentialsRequest, error) {
err := r.ParseForm()
if err != nil {
return nil, oidc.ErrInvalidRequest().WithDescription("error parsing form").WithParent(err)
}
request := new(oidc.ClientCredentialsRequest)
err = decoder.Decode(request, r.Form)
if err != nil {
return nil, oidc.ErrInvalidRequest().WithDescription("error decoding form").WithParent(err)
}
if clientID, clientSecret, ok := r.BasicAuth(); ok {
clientID, err = url.QueryUnescape(clientID)
if err != nil {
return nil, oidc.ErrInvalidClient().WithDescription("invalid basic auth header").WithParent(err)
}
clientSecret, err = url.QueryUnescape(clientSecret)
if err != nil {
return nil, oidc.ErrInvalidClient().WithDescription("invalid basic auth header").WithParent(err)
}
request.ClientID = clientID
request.ClientSecret = clientSecret
}
return request, nil
}
// ValidateClientCredentialsRequest validates the client_credentials request parameters including authorization check of the client
// and returns a TokenRequest and Client implementation to be used in the client_credentials response, resp. creation of the corresponding access_token.
func ValidateClientCredentialsRequest(ctx context.Context, request *oidc.ClientCredentialsRequest, exchanger Exchanger) (TokenRequest, Client, error) {
storage, ok := exchanger.Storage().(ClientCredentialsStorage)
if !ok {
return nil, nil, oidc.ErrUnsupportedGrantType().WithDescription("client_credentials grant not supported")
}
client, err := AuthorizeClientCredentialsClient(ctx, request, storage)
if err != nil {
return nil, nil, err
}
tokenRequest, err := storage.ClientCredentialsTokenRequest(ctx, request.ClientID, request.Scope)
if err != nil {
return nil, nil, err
}
return tokenRequest, client, nil
}
func AuthorizeClientCredentialsClient(ctx context.Context, request *oidc.ClientCredentialsRequest, storage ClientCredentialsStorage) (Client, error) {
client, err := storage.ClientCredentials(ctx, request.ClientID, request.ClientSecret)
if err != nil {
return nil, oidc.ErrInvalidClient().WithParent(err)
}
if !ValidateGrantType(client, oidc.GrantTypeClientCredentials) {
return nil, oidc.ErrUnauthorizedClient()
}
return client, nil
}
func CreateClientCredentialsTokenResponse(ctx context.Context, tokenRequest TokenRequest, creator TokenCreator, client Client) (*oidc.AccessTokenResponse, error) {
accessToken, _, validity, err := CreateAccessToken(ctx, tokenRequest, client.AccessTokenType(), creator, client, "")
if err != nil {
return nil, err
}
return &oidc.AccessTokenResponse{
AccessToken: accessToken,
TokenType: oidc.BearerToken,
ExpiresIn: uint64(validity.Seconds()),
}, nil
}

View file

@ -18,6 +18,7 @@ type Exchanger interface {
GrantTypeRefreshTokenSupported() bool GrantTypeRefreshTokenSupported() bool
GrantTypeTokenExchangeSupported() bool GrantTypeTokenExchangeSupported() bool
GrantTypeJWTAuthorizationSupported() bool GrantTypeJWTAuthorizationSupported() bool
GrantTypeClientCredentialsSupported() bool
} }
func tokenHandler(exchanger Exchanger) func(w http.ResponseWriter, r *http.Request) { func tokenHandler(exchanger Exchanger) func(w http.ResponseWriter, r *http.Request) {
@ -42,6 +43,11 @@ func tokenHandler(exchanger Exchanger) func(w http.ResponseWriter, r *http.Reque
TokenExchange(w, r, exchanger) TokenExchange(w, r, exchanger)
return return
} }
case string(oidc.GrantTypeClientCredentials):
if exchanger.GrantTypeClientCredentialsSupported() {
ClientCredentialsExchange(w, r, exchanger)
return
}
case "": case "":
RequestError(w, r, oidc.ErrInvalidRequest().WithDescription("grant_type missing")) RequestError(w, r, oidc.ErrInvalidRequest().WithDescription("grant_type missing"))
return return