auth

package module
v0.7.7 Latest Latest
Warning

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

Go to latest
Published: Jan 19, 2024 License: MIT Imports: 20 Imported by: 10

README

Auth

Authenticating and authorizing client/server applications.

Usage

go get github.com/worldline-go/auth

Check http example: example/http

Packages

- echo middleware -> pkg/authecho

Client

Client is usefull to send request with oauth2 token.

First set a provider.

var providerClient = auth.Provider{
	Keycloak: &providers.KeyCloak{
		ClientID:     "test",
		ClientSecret: "my_client_secret",
        // Keycloak server url
		BaseURL:      "http://localhost:8080",
		Realm:        "finops",
        // Scopes is optional
		Scopes:       []string{"openid", "profile", "email", "offline_access"},
	},
}

Then when you create a http.Client you can use the oauth2 transport.

provider := providerClient.ActiveProvider()
if == nil {
	return fmt.Errorf("no active provider")
}

roundTripper, err := provider.RoundTripper(ctx, http.DefaultTransport)
if err != nil {
	return fmt.Errorf("creating round tripper: %w", err)
}

client := &http.Client{
    Transport: roundTripper,
}

Now you can make request with this client.

Server

Check the token in the request. Just need to url of keycloak server and the realm.

var providerServer = auth.Provider{
	Keycloak: &providers.KeyCloak{
        // Keycloak server url
		BaseURL: "http://localhost:8080",
		Realm:   "finops",
	},
}

Then you can check the token in the request.

This is the http based, very simple function but check the our echo middleware to much more advanced operations.

provider := providerServer.ActiveProvider()
if provider == nil {
	return fmt.Errorf("no active provider")
}

keyFunc, err := provider.JWTKeyFunc(auth.WithContext(ctx))
if err != nil {
	return fmt.Errorf("creating parser: %w", err)
}

// if you don't use the context cancelation, you can use this
// defer keyFunc.EndBackground()

// Check the token in the request
claimsValue := claims.Custom{}
token, err := keyFunc.Parser(tokenToCheck, &claimsValue)
if err != nil {
    return fmt.Errorf("token 👎: %w", err)
}

Redirection Flow

When enabled redirection in the middleware, the user will be redirected to the oauth2 login page.

This is not a standard flow and we can change update it any time.
Code for echo middleware is here.

Redirection Flow

Documentation

Index

Constants

View Source
const (
	ProviderKeycloakKey = "keycloak"
	ProviderGenericKey  = "generic"
	ProviderNoopKey     = "noop"
)
View Source
const NoopKey = "noop"

Variables

View Source
var DefaultExpireDuration = time.Second * 10

DefaultExpireDuration is the default duration to check if the access token is about to expire.

View Source
var ErrKIDNotFound = keyfunc.ErrKIDNotFound
View Source
var IntrospectKey = "introspect"

Functions

func GenerateKeyID added in v0.7.1

func GenerateKeyID(random []byte) string

func GetOptionJWK added in v0.7.1

func GetOptionJWK(opts ...OptionJWK) optionsJWK

func IsRefreshNeed added in v0.4.1

func IsRefreshNeed(accessToken string) (bool, error)

IsRefreshNeed checks if the access token is about to expire.

func MapOptionKeyfunc added in v0.7.1

func MapOptionKeyfunc(opt optionsJWK) keyfunc.Options

func MultiJWTKeyFunc added in v0.7.1

func MultiJWTKeyFunc(providers []InfProviderCert, opts ...OptionJWK) (models.InfKeyFunc, error)

MultiJWTKeyFunc returns a jwt.Keyfunc with multiple keyfunc.

Doesn't support introspect and noops, it will ignore them.

func ParseUnverified added in v0.4.8

func ParseUnverified(tokenString string, claims jwt.Claims) (*jwt.Token, []string, error)

Types

type InfProvider added in v0.4.0

type InfProvider interface {
	ClientConfig() (*clientcredentials.Config, error)

	GetCertURL() string
	GetTokenURL() string
	GetTokenURLExternal() string
	GetAuthURL() string
	GetAuthURLExternal() string
	GetClientID() string
	GetClientIDExternal() string
	GetClientSecret() string
	GetClientSecretExternal() string
	GetScopes() []string
	GetIntrospectURL() string
	GetLogoutURL() string
	GetLogoutURLExternal() string
}

type InfProviderCert added in v0.7.1

type InfProviderCert interface {
	GetCertURL() string
	IsNoop() bool
}

type InfProviderExtra added in v0.4.0

type InfProviderExtra interface {
	InfProvider
	// JWTKeyFunc returns the JWT key used to verify the token.
	JWTKeyFunc(opts ...OptionJWK) (models.InfKeyFuncParser, error)
	IsNoop() bool
	NewOauth2Shared(ctx context.Context) (*OAuth2Shared, error)
	RoundTripper(ctx context.Context, transport http.RoundTripper) (http.RoundTripper, error)
	RoundTripperWrapper(cfg *clientcredentials.Config) func(ctx context.Context, transport http.RoundTripper) http.RoundTripper
}

type IntrospectJWTKey added in v0.4.8

type IntrospectJWTKey struct {
	URL          string
	ClientID     string
	ClientSecret string

	Client *http.Client
	Ctx    context.Context
}

func (IntrospectJWTKey) CheckIntrospect added in v0.4.8

func (i IntrospectJWTKey) CheckIntrospect(token string) error

func (IntrospectJWTKey) Keyfunc added in v0.4.8

func (IntrospectJWTKey) Keyfunc(token *jwt.Token) (interface{}, error)

func (IntrospectJWTKey) ParseWithClaims added in v0.7.0

func (i IntrospectJWTKey) ParseWithClaims(tokenString string, claims jwt.Claims) (*jwt.Token, error)

type JWT added in v0.7.1

type JWT struct {
	// contains filtered or unexported fields
}

func NewJWT added in v0.7.2

func NewJWT(opts ...OptionJWT) (*JWT, error)

NewJWT function get secret key and options and return a new JWT instance.

Default expiration function is time.Now().Add(time.Hour).Unix().

func (*JWT) ExpFunc added in v0.7.1

func (t *JWT) ExpFunc() int64

func (*JWT) Generate added in v0.7.1

func (t *JWT) Generate(mapClaims map[string]interface{}, expDate int64) (string, error)

Generate function get custom values and add 'exp' as expires at with expDate argument with unix format.

func (*JWT) GivenKey added in v0.7.1

func (t *JWT) GivenKey() map[string]keyfunc.GivenKey

GivenKey useful for mixing other keys in jwks function.

jwks, err := authProvider.JWTKeyFunc(auth.WithContext(ctx), auth.WithGivenKeys(
	serverJWT.GivenKey(),
))

func (*JWT) Jwks added in v0.7.1

func (t *JWT) Jwks() models.InfKeyFunc

func (*JWT) Parse added in v0.7.1

func (t *JWT) Parse(tokenStr string, claims jwt.Claims) (*jwt.Token, error)

Parse is validating and getting claims.

func (*JWT) Renew added in v0.7.1

func (t *JWT) Renew(tokenStr string, expDate int64) (string, error)

Renew token with not changing claims.

type JwkKeyFuncParse added in v0.7.1

type JwkKeyFuncParse struct {
	KeyFunc func(token *jwt.Token) (interface{}, error)
}

func (*JwkKeyFuncParse) Keyfunc added in v0.7.1

func (j *JwkKeyFuncParse) Keyfunc(token *jwt.Token) (interface{}, error)

func (*JwkKeyFuncParse) ParseWithClaims added in v0.7.1

func (j *JwkKeyFuncParse) ParseWithClaims(tokenString string, claims jwt.Claims) (*jwt.Token, error)

type KeyFuncMulti added in v0.7.1

type KeyFuncMulti struct {
	// contains filtered or unexported fields
}

func (*KeyFuncMulti) KeySelectorFirst added in v0.7.1

func (k *KeyFuncMulti) KeySelectorFirst(multiJWKS *keyfunc.MultipleJWKS, token *jwt.Token) (interface{}, error)

func (*KeyFuncMulti) Keyfunc added in v0.7.1

func (k *KeyFuncMulti) Keyfunc(token *jwt.Token) (interface{}, error)

type Noop added in v0.4.0

type Noop struct{}

func (Noop) ClientConfig added in v0.4.0

func (Noop) ClientConfig() (*clientcredentials.Config, error)

func (Noop) GetAuthURL added in v0.4.0

func (Noop) GetAuthURL() string

func (Noop) GetAuthURLExternal added in v0.5.0

func (Noop) GetAuthURLExternal() string

func (Noop) GetCertURL added in v0.4.0

func (Noop) GetCertURL() string

func (Noop) GetClientID added in v0.4.0

func (Noop) GetClientID() string

func (Noop) GetClientIDExternal added in v0.5.0

func (Noop) GetClientIDExternal() string

func (Noop) GetClientSecret added in v0.4.0

func (Noop) GetClientSecret() string

func (Noop) GetClientSecretExternal added in v0.5.0

func (Noop) GetClientSecretExternal() string

func (Noop) GetIntrospectURL added in v0.4.8

func (Noop) GetIntrospectURL() string

func (Noop) GetLogoutURL added in v0.7.1

func (Noop) GetLogoutURL() string

func (Noop) GetLogoutURLExternal added in v0.7.1

func (Noop) GetLogoutURLExternal() string

func (Noop) GetScopes added in v0.4.8

func (Noop) GetScopes() []string

func (Noop) GetTokenURL added in v0.4.0

func (Noop) GetTokenURL() string

func (Noop) GetTokenURLExternal added in v0.5.0

func (Noop) GetTokenURLExternal() string

func (Noop) IsNoop added in v0.4.0

func (Noop) IsNoop() bool

func (Noop) JWTKeyFunc added in v0.4.0

func (Noop) JWTKeyFunc(opts ...OptionJWK) (models.InfKeyFuncParser, error)

func (Noop) NewOauth2Shared added in v0.6.3

func (Noop) NewOauth2Shared(_ context.Context) (*OAuth2Shared, error)

func (Noop) RoundTripper added in v0.4.2

func (Noop) RoundTripper(_ context.Context, transport http.RoundTripper) (http.RoundTripper, error)

func (Noop) RoundTripperWrapper added in v0.4.5

func (Noop) RoundTripperWrapper(_ *clientcredentials.Config) func(_ context.Context, transport http.RoundTripper) http.RoundTripper

type NoopJWTKey added in v0.4.0

type NoopJWTKey struct{}

func (NoopJWTKey) EndBackground added in v0.4.0

func (NoopJWTKey) EndBackground()

func (NoopJWTKey) Keyfunc added in v0.4.0

func (NoopJWTKey) Keyfunc(_ *jwt.Token) (interface{}, error)

func (NoopJWTKey) ParseWithClaims added in v0.7.0

func (n NoopJWTKey) ParseWithClaims(tokenString string, claims jwt.Claims) (*jwt.Token, error)

type OAuth2Shared added in v0.6.3

type OAuth2Shared struct {
	Source oauth2.TokenSource
}

func (OAuth2Shared) RoundTripper added in v0.6.3

func (o OAuth2Shared) RoundTripper(_ context.Context, transport http.RoundTripper) (http.RoundTripper, error)

RoundTripper returns a new RoundTripper that adds an OAuth2 Transport.

If Source is nil, returns transport as-is.

type Oauth2Transport added in v0.5.1

type Oauth2Transport struct {
	Transport oauth2.Transport
}

Oauth2Transport wraps oauth2.Transport to suspend CancelRequest.

func (*Oauth2Transport) RoundTrip added in v0.5.1

func (t *Oauth2Transport) RoundTrip(req *http.Request) (*http.Response, error)

type OptionActiveProvider added in v0.4.0

type OptionActiveProvider func(options *optionsActiveProvider)

func WithActive added in v0.6.2

func WithActive(provider string) OptionActiveProvider

func WithNoop added in v0.4.0

func WithNoop(v bool) OptionActiveProvider

WithNoop sets the active provider to noop.

type OptionJWK

type OptionJWK func(options *optionsJWK)

func WithClient added in v0.2.2

func WithClient(client *http.Client) OptionJWK

WithClient is used to set the http.Client used to fetch the JWKs.

func WithContext added in v0.4.5

func WithContext(ctx context.Context) OptionJWK

WithContext is used to set the context used to fetch the JWKs.

func WithIntrospect added in v0.4.8

func WithIntrospect(v bool) OptionJWK

func WithKeyFunc added in v0.7.1

func WithKeyFunc(keyFunc models.InfKeyFunc) OptionJWK

WithGivenKeys is used to set the given keys used to verify the token.

Return ErrKIDNotFound if the kid is not found.

Example:

// Create the JWKS from the given keys.
givenKeys := map[string]keyfunc.GivenKey{
	"my-key-id": keyfunc.NewGivenHMAC(...),
}
jwks := keyfunc.NewGiven(givenKeys)

func WithRefreshErrorHandler

func WithRefreshErrorHandler(fn func(err error)) OptionJWK

WithRefreshErrorHandler sets the refresh error handler for the jwt.Key.

func WithRefreshInterval added in v0.2.0

func WithRefreshInterval(d time.Duration) OptionJWK

WithRefreshInterval sets the refresh interval for the jwt.Keyfunc default is 5 minutes.

type OptionJWT added in v0.7.2

type OptionJWT func(options *optionJWT)

func WithECDSAPrivateKey added in v0.7.1

func WithECDSAPrivateKey(secret *ecdsa.PrivateKey) OptionJWT

func WithECDSAPublicKey added in v0.7.1

func WithECDSAPublicKey(secret *ecdsa.PublicKey) OptionJWT

func WithED25519PrivateKey added in v0.7.1

func WithED25519PrivateKey(secret ed25519.PrivateKey) OptionJWT

func WithED25519PublicKey added in v0.7.1

func WithED25519PublicKey(secret ed25519.PublicKey) OptionJWT

func WithExpFunc added in v0.7.1

func WithExpFunc(fn func() int64) OptionJWT

WithExpFunc sets the expiration function for the JWT.

func WithKID added in v0.7.1

func WithKID(kid string) OptionJWT

WithKID sets the key ID for the JWT.

func WithMethod added in v0.7.1

func WithMethod(method jwt.SigningMethod) OptionJWT

WithMethod sets the signing method for the JWT.

func WithRSAPrivateKey added in v0.7.1

func WithRSAPrivateKey(secret *rsa.PrivateKey) OptionJWT

func WithRSAPublicKey added in v0.7.1

func WithRSAPublicKey(secret *rsa.PublicKey) OptionJWT

func WithSecretByte added in v0.7.1

func WithSecretByte(secret []byte) OptionJWT

type Provider

type Provider struct {
	// Active is the name of the active provider, if empty the first provider is used.
	//
	// If set to "noop" the Noop provider is used.
	Active   string              `cfg:"active"`
	Keycloak *providers.KeyCloak `cfg:"keycloak"`
	Generic  *providers.Generic  `cfg:"generic"`
}

func (*Provider) ActiveProvider

func (p *Provider) ActiveProvider(opts ...OptionActiveProvider) (ret InfProviderExtra)

ActiveProvider returns the active provider or the first provider if none is active.

Returns nil if no provider is configured.

func (Provider) SetActiveProvider

func (p Provider) SetActiveProvider(name string) *Provider

SetActiveProvider return the provider with the given name as active without modifying the original provider.

type ProviderExtra added in v0.4.0

type ProviderExtra struct {
	InfProvider
	// contains filtered or unexported fields
}

func (*ProviderExtra) IsNoop added in v0.4.0

func (p *ProviderExtra) IsNoop() bool

func (*ProviderExtra) JWTKeyFunc added in v0.4.0

func (p *ProviderExtra) JWTKeyFunc(opts ...OptionJWK) (models.InfKeyFuncParser, error)

JWTKeyFunc returns a jwt.Keyfunc.

Need GetCertURL in provider.

If introspect is true, the introspect endpoint is used to verify the token. Use Parser function for introspect, not keyfunc.

func (*ProviderExtra) NewOauth2Shared added in v0.6.3

func (p *ProviderExtra) NewOauth2Shared(ctx context.Context) (*OAuth2Shared, error)

func (*ProviderExtra) RoundTripper added in v0.4.2

func (p *ProviderExtra) RoundTripper(ctx context.Context, transport http.RoundTripper) (http.RoundTripper, error)

RoundTripper returns a new RoundTripper that adds an OAuth2 Transport.

Uses provider's ClientConfig.

func (*ProviderExtra) RoundTripperWrapper added in v0.4.5

func (p *ProviderExtra) RoundTripperWrapper(cfg *clientcredentials.Config) func(ctx context.Context, transport http.RoundTripper) http.RoundTripper

type RestIntrospect added in v0.4.8

type RestIntrospect struct {
	Active bool `json:"active"`
}

type Token added in v0.7.0

type Token = oauth2.Token

Directories

Path Synopsis
example
http Module
middlewares
authecho Module
pkg

Jump to

Keyboard shortcuts

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