session

package
v0.9.3 Latest Latest
Warning

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

Go to latest
Published: Aug 4, 2026 License: MIT Imports: 23 Imported by: 0

Documentation

Index

Constants

View Source
const (
	SignupActionSignup       = "signup"
	SignupActionVerify       = "signup-verify"
	SignupActionReset        = "password-reset"
	SignupActionResetConfirm = "password-reset-confirm"
)

Signup actions an issuer can run in-process for the login page.

View Source
const (
	CtxTokenHeaderKey     = "token_header"
	CtxTokenHeaderDelKey  = "token_header_delete"
	CtxDisableRedirectKey = "disable_redirect"
	CtxCookieNameKey      = "cookie_name"
)

Variables

View Source
var (
	ErrKIDNotFound  = jwks.ErrKIDNotFound
	ErrTokenInvalid = fmt.Errorf("token is invalid")
)
View Source
var (
	TokenKey    = "token"
	ProviderKey = "provider"
)
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 ErrMultipleJWKSSize = errors.New("multiple JWKS must have one or more remote JWK Set resources")

ErrMultipleJWKSSize is returned when GetMultiple is called without any remote JWK Set resource.

View Source
var GlobalRegistry = &Registry{
	Store: make(map[string]*Session),
}
View Source
var IssuerRegistry = &issuerRegistry{
	store: make(map[string]InfIssuer),
}

IssuerRegistry holds in-process token issuers by middleware name.

Functions

func GetOptionJWK

func GetOptionJWK(opts ...OptionJWK) optionsJWK

func IsRefreshNeed added in v0.7.11

func IsRefreshNeed(accessToken string) (bool, error)

IsRefreshNeed checks if the access token is about to expire.

func MapOptionJWKS added in v0.9.2

func MapOptionJWKS(opt optionsJWK) jwks.Options

Types

type Action

type Action struct {
	Active string `cfg:"active"`
	Token  *Token `cfg:"token"`
}

type AuthHeaderStyle

type AuthHeaderStyle int

AuthHeaderStyle is a type to set Authorization header style.

const (
	AuthHeaderStyleBasic AuthHeaderStyle = iota
	AuthHeaderStyleBearerSecret
	AuthHeaderStyleParams
)

type HostCookieName

type HostCookieName struct {
	// Host as "localhost:8082"
	Host  string `cfg:"host"`
	Regex string `cfg:"regex"`

	CookieName string `cfg:"cookie_name"`
	// contains filtered or unexported fields
}

type InfAPIKey added in v0.9.0

type InfAPIKey interface {
	APIKeyData(ctx context.Context, key string) ([]byte, error)
}

InfAPIKey is implemented by issuers that can validate static API keys directly. It returns claim-shaped identity JSON for the key principal; no token exchange is involved and validation hits the issuer's database on every call, so deleted/disabled keys fail immediately.

type InfIssuer added in v0.9.0

type InfIssuer interface {
	// Keyfunc returns the public key for tokens signed by this issuer.
	// It must return ErrKIDNotFound when the token was signed by someone else.
	Keyfunc(token *jwt.Token) (any, error)
	// IssueToken runs an OAuth2 token request (password, refresh_token, ...)
	// in-process and returns the raw JSON body with its HTTP status code.
	IssueToken(ctx context.Context, form url.Values) ([]byte, int, error)
}

InfIssuer is an in-process token issuer, like the auth middleware.

A provider configured with `auth_middleware: <name>` resolves the issuer from IssuerRegistry instead of calling cert_url/token_url over HTTP.

type InfKeyFunc

type InfKeyFunc interface {
	Keyfunc(token *jwt.Token) (any, error)
}

type InfKeyFuncParser

type InfKeyFuncParser interface {
	InfKeyFunc
	ParseWithClaims(tokenString string, claims jwt.Claims) (*jwt.Token, error)
}

type InfPasskey added in v0.9.0

type InfPasskey interface {
	PasskeyToken(ctx context.Context, orig *http.Request, body []byte) ([]byte, int, error)
}

InfPasskey is implemented by issuers that support WebAuthn (passkey) login. The body is the begin/finish JSON payload; the original request carries host/scheme information for relying-party derivation.

type InfProviderCert

type InfProviderCert interface {
	GetCertURL() string
	GetName() string
}

type InfSignup added in v0.9.0

type InfSignup interface {
	SignupFeatures() SignupFeatures
	// SignupAction runs one of the SignupAction* requests in-process; body is
	// the JSON payload including client credentials.
	SignupAction(ctx context.Context, action string, body []byte) ([]byte, int, error)
}

InfSignup is implemented by issuers that support self-registration and password reset over email (the auth middleware "signup" namespace).

type JwkKeyFuncParse

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

func MultiJWTKeyFunc

func MultiJWTKeyFunc(providers []InfProviderCert, opts ...OptionJWK) (*JwkKeyFuncParse, error)

MultiJWTKeyFunc returns a jwt.Keyfunc with multiple JWK Sets.

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

func (*JwkKeyFuncParse) Keyfunc

func (j *JwkKeyFuncParse) Keyfunc(token *jwt.Token) (any, error)

func (*JwkKeyFuncParse) ParseWithClaims

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

type KeyFound

type KeyFound struct {
	Key  any
	Name string
}

func KeySelectorFirst

func KeySelectorFirst(multiJWKS *MultipleJWKS, token *jwt.Token) (*KeyFound, error)

KeySelectorFirst returns the first key found in the multiple JWK Sets.

type KeyFuncMulti

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

func (*KeyFuncMulti) KeySelectorFirst

func (k *KeyFuncMulti) KeySelectorFirst(multiJWKS *MultipleJWKS, token *jwt.Token) (any, error)

func (*KeyFuncMulti) Keyfunc

func (k *KeyFuncMulti) Keyfunc(token *jwt.Token) (any, error)

type MetaData

type MetaData struct {
	Error string `json:"error"`
}

type MultipleJWKS

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

MultipleJWKS manages multiple JWKS and has a field for jwt.Keyfunc.

func GetMultiple

func GetMultiple(multiple map[MultipleJWKSKey]jwks.Options, options MultipleOptions) (multiJWKS *MultipleJWKS, err error)

GetMultiple creates a new MultipleJWKS. A map of length one or more JWKS URLs to Options is required.

func (*MultipleJWKS) Keyfunc

func (m *MultipleJWKS) Keyfunc(token *jwt.Token) (any, error)

Keyfunc matches the signature of github.com/golang-jwt/jwt/v5's jwt.Keyfunc function.

type MultipleJWKSKey

type MultipleJWKSKey struct {
	URL  string
	Name string
}

type MultipleOptions

type MultipleOptions struct {
	KeySelector func(multiJWKS *MultipleJWKS, token *jwt.Token) (key any, err error)
}

type Oauth2

type Oauth2 struct {
	// ClientID is the application's ID.
	ClientID string `cfg:"client_id"`
	// ClientSecret is the application's secret.
	ClientSecret string `cfg:"client_secret" log:"false"`
	// Scope specifies optional requested permissions.
	Scopes []string `cfg:"scopes"`
	// CertURL is the resource server's public key URL.
	CertURL string `cfg:"cert_url"`
	// IntrospectURL is the check the active or not with request.
	IntrospectURL string `cfg:"introspect_url"`
	// UserInfoURL is the get information about user.
	UserInfoURL string `cfg:"userinfo_url"`
	// RevocationURL for token revocation.
	RevocationURL string `cfg:"revocation_url"`
	// AuthURL is the resource server's authorization endpoint
	// use for redirection to login page.
	AuthURL string `cfg:"auth_url"`
	// TokenURL is the resource server's token endpoint URL.
	TokenURL  string `cfg:"token_url"`
	LogoutURL string `cfg:"logout_url"`
	// PasskeyURL is the WebAuthn begin/finish endpoint of a remote auth
	// middleware (e.g. https://auth.example.com/auth/oauth2/passkey).
	// Not needed when the provider uses auth_middleware (in-process).
	PasskeyURL string `cfg:"passkey_url"`
	// APIKeyURL is the static API key validation endpoint of a remote auth
	// middleware (e.g. https://auth.example.com/auth/oauth2/api-key).
	// Not needed when the provider uses auth_middleware (in-process).
	APIKeyURL string `cfg:"api_key_url"`
	// SignupURL is the self-registration endpoint of a remote auth middleware
	// (e.g. https://auth.example.com/auth/oauth2/signup); the verify endpoint
	// is derived as SignupURL + "/verify".
	// Not needed when the provider uses auth_middleware (in-process).
	SignupURL string `cfg:"signup_url"`
	// PasswordResetURL is the forgot-password endpoint of a remote auth
	// middleware (e.g. https://auth.example.com/auth/oauth2/password-reset);
	// the confirm endpoint is derived as PasswordResetURL + "/confirm".
	// Not needed when the provider uses auth_middleware (in-process).
	PasswordResetURL string `cfg:"password_reset_url"`
	// AuthHeaderStyle is optional. If not set, AuthHeaderStyleBasic will be used.
	AuthHeaderStyle AuthHeaderStyle
}

type OptionJWK

type OptionJWK func(options *optionsJWK)

func WithClient

func WithClient(client *http.Client) OptionJWK

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

func WithContext

func WithContext(ctx context.Context) OptionJWK

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

func WithIntrospect

func WithIntrospect(v bool) OptionJWK

func WithKeyFunc

func WithKeyFunc(keyFunc InfKeyFunc) OptionJWK

WithKeyFunc is used to set the given key function used to verify the token before checking the remote JWK Sets.

The key function must return ErrKIDNotFound if the kid is not found so the lookup falls through to the remote JWK Sets.

func WithRefreshErrorHandler

func WithRefreshErrorHandler(fn func(err error)) OptionJWK

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

func WithRefreshInterval

func WithRefreshInterval(d time.Duration) OptionJWK

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

type Options

type Options struct {
	Path     string `cfg:"path"`
	MaxAge   int    `cfg:"max_age"`
	Domain   string `cfg:"domain"`
	Secure   bool   `cfg:"secure"`
	HttpOnly bool   `cfg:"http_only"`
	// SameSite for Lax 2, Strict 3, None 4.
	SameSite http.SameSite `cfg:"same_site"`
}

type Provider

type Provider struct {
	Name   string  `cfg:"name"`
	Oauth2 *Oauth2 `cfg:"oauth2"`
	// AuthMiddleware is the name of an in-process auth middleware instance.
	// When set, token validation and refresh go directly to that middleware
	// instead of cert_url/token_url over HTTP. oauth2.client_id should match
	// an OAuth client registered in the auth middleware.
	AuthMiddleware string `cfg:"auth_middleware"`
	// Passkey advertises WebAuthn login on the login page for this provider.
	// Requires auth_middleware (in-process) or oauth2.passkey_url (remote).
	Passkey bool `cfg:"passkey"`
	// XUser header set from token claims. Default is email and preferred_username.
	// It set first found value.
	XUser []string `cfg:"x_user"`
	// ClaimHeader is use to map claim to header.
	//   - Example: claim_header = {"X-User-Id": "preferred_username", "X-User-Email": "email"}
	//   - Default is adding "X-User-Id" header with "preferred_username" claim.
	//   - Set empty value to delete the header.
	ClaimHeader      map[string]string `cfg:"claim_header"`
	EmailVerifyCheck bool              `cfg:"email_verify_check"`
	// PasswordFlow is use password flow to get token.
	PasswordFlow bool `cfg:"password_flow"`
	// APIKey enables static X-API-Key authentication at the session layer.
	// The key is validated directly (in-process via auth_middleware or over
	// oauth2.api_key_url); no token exchange happens and downstream services
	// receive the key principal's claims/X-User.
	APIKey bool `cfg:"api_key"`
	// APIKeyHeader is the header carrying the raw API key. Default X-API-Key.
	APIKeyHeader string `cfg:"api_key_header"`
	// Priority is use to sort provider.
	Priority int `cfg:"priority"`
	// Hide is use to hide provider.
	Hide bool `cfg:"hide"`
}

type ProviderWrapper

type ProviderWrapper struct {
	Name    string
	Generic *providers.Generic
}

func (*ProviderWrapper) GetCertURL

func (p *ProviderWrapper) GetCertURL() string

func (*ProviderWrapper) GetName

func (p *ProviderWrapper) GetName() string

type Registry

type Registry struct {
	Store map[string]*Session
	// contains filtered or unexported fields
}

func (*Registry) Get

func (r *Registry) Get(name string) *Session

func (*Registry) Set

func (r *Registry) Set(name string, store *Session)

type Session

type Session struct {
	// SessionKey is the default signing key for configured session stores.
	// A store-specific session_key takes precedence when set.
	SessionKey string `cfg:"session_key"`
	Store      Store  `cfg:"store"`
	// Options for main cookie.
	Options Options `cfg:"options"`

	// CookieName for default cookie name.
	// Overwrite this value with 'cookie_name' ctx value.
	CookieName string `cfg:"cookie_name"`
	// CookieNameHosts for cookie name by host with regexp.
	CookieNameHosts []HostCookieName `cfg:"cookie_name_hosts"`

	Action   Action              `cfg:"action"`
	Provider map[string]Provider `cfg:"provider"`
	// SetProvider is the default provider to set for refresing tokens.
	SetProvider string `cfg:"set_provider"`
	// contains filtered or unexported fields
}

func (*Session) DelToken

func (m *Session) DelToken(w http.ResponseWriter, r *http.Request) error

func (*Session) Do

func (m *Session) Do(next http.Handler, w http.ResponseWriter, r *http.Request)

func (*Session) GetCookieName

func (m *Session) GetCookieName(r *http.Request) string

func (*Session) GetStore

func (m *Session) GetStore() StoreInf

func (*Session) GetToken

func (m *Session) GetToken(r *http.Request) (*TokenData, *Oauth2, error)

func (*Session) Init

func (m *Session) Init(ctx context.Context, name string) error

func (*Session) IsLogged

func (m *Session) IsLogged(w http.ResponseWriter, r *http.Request) (*claims.Custom, bool, error)

IsLogged check token is exist and valid.

func (*Session) Middleware

func (m *Session) Middleware(ctx context.Context, name string) (func(http.Handler) http.Handler, error)

func (*Session) RedirectToLogin

func (m *Session) RedirectToLogin(w http.ResponseWriter, r *http.Request, addRedirectPath bool, removeSession bool)

func (*Session) RedirectToMain

func (m *Session) RedirectToMain(w http.ResponseWriter, r *http.Request)

func (*Session) SetAction

func (m *Session) SetAction() error

func (*Session) SetStore

func (m *Session) SetStore(ctx context.Context) error

func (*Session) SetToken

func (m *Session) SetToken(w http.ResponseWriter, r *http.Request, token []byte, providerName string) error

type SignupFeatures added in v0.9.0

type SignupFeatures struct {
	Signup            bool `json:"signup"`
	PasswordReset     bool `json:"password_reset"`
	PasswordMinLength int  `json:"password_min_length"`
}

SignupFeatures reports which self-service account flows are enabled on the issuer right now; the login page uses it to show/hide signup and forgot-password live without restarts.

type Store

type Store struct {
	Active string       `cfg:"active"`
	Redis  *store.Redis `cfg:"redis"`
	File   *store.File  `cfg:"file"`
}

type StoreInf

type StoreInf interface {
	Get(r *http.Request, name string) (*sessions.Session, error)
}

type Token

type Token struct {
	LoginPath          string `cfg:"login_path"`
	DisableRefresh     bool   `cfg:"disable_refresh"`
	InsecureSkipVerify bool   `cfg:"insecure_skip_verify"`
	// contains filtered or unexported fields
}

func (*Token) GetKeyFunc

func (t *Token) GetKeyFunc() InfKeyFuncParser

type TokenData

type TokenData struct {
	AccessToken      string `json:"access_token"`
	ExpiresIn        int    `json:"expires_in"`
	RefreshExpiresIn int    `json:"refresh_expires_in"`
	RefreshToken     string `json:"refresh_token"`
	TokenType        string `json:"token_type"`
	NotBeforePolicy  int    `json:"not-before-policy"`
	SessionState     string `json:"session_state"`
	Scope            string `json:"scope"`
	IDToken          string `json:"id_token"`
}

func ParseToken

func ParseToken(v []byte) (*TokenData, error)

func ParseToken64

func ParseToken64(v string) (*TokenData, error)

Parse64 parse the cookie

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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