auth0

package
v0.243.0 Latest Latest
Warning

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

Go to latest
Published: Oct 7, 2026 License: AGPL-3.0 Imports: 26 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// ConfigEnvPrefix is the prefix applied to environment variables for configuring Auth0.
	ConfigEnvPrefix = "AUTH0_"
)

Variables

View Source
var ErrInvalidToken = errors.New("token is invalid")
View Source
var ErrNoIDToken = errors.New("no id_token field in oauth2 token")
View Source
var LoadAuthenticator = sync.OnceValues(func() (*Authenticator, error) {
	err := loadConfigOnce()
	if err != nil {
		return nil, fmt.Errorf("load config: %w", err)
	}

	provider, err := oidc.NewProvider(
		context.Background(),
		"https://"+cfg.Domain+"/",
	)
	if err != nil {
		return nil, fmt.Errorf("create provider: %w", err)
	}

	conf := oauth2.Config{
		ClientID:     cfg.ClientID,
		ClientSecret: cfg.ClientSecret,
		RedirectURL:  cfg.CallbackURL,
		Endpoint:     provider.Endpoint(),
		Scopes:       []string{oidc.ScopeOpenID, oidc.ScopeOfflineAccess, "profile", "email"},
	}

	sessionMgr, err := session.Load()
	if err != nil {
		return nil, fmt.Errorf("load session manager: %w", err)
	}

	httpClient := httpclient.New().
		SetTransport(&http.Transport{
			Proxy:                 http.ProxyFromEnvironment,
			DialContext:           httpclient.SecureDialer.DialContext,
			ForceAttemptHTTP2:     true,
			TLSHandshakeTimeout:   5 * time.Second,
			ResponseHeaderTimeout: 10 * time.Second,
			IdleConnTimeout:       90 * time.Second,
			MaxIdleConns:          100,
			MaxIdleConnsPerHost:   20,
		}).
		SetTimeout(15 * time.Second).
		SetDebug(false)

	return &Authenticator{
		Provider:       provider,
		Config:         conf,
		httpClient:     httpClient,
		sessionManager: sessionMgr,
	}, nil
})

LoadAuthenticator will the setup and initialisation of the Auth0 tenant. It can be called multiple times but will only perform initialisation once (so it can be lazily loaded by calling it before any Auth0 actions).

View Source
var LoadManager = sync.OnceValues(func() (*Manager, error) {
	if err := loadConfigOnce(); err != nil {
		return nil, fmt.Errorf("load config: %w", err)
	}

	mgmt, err := client.New(
		cfg.MgmtDomain,
		option.WithClientCredentials(
			context.Background(),
			cfg.ClientID,
			cfg.ClientSecret,
		),
	)
	if err != nil {
		return nil, fmt.Errorf("new management api connection: %w", err)
	}

	return &Manager{Management: mgmt}, nil
})

LoadManager loads a connection to the Auth0 management API.

Functions

This section is empty.

Types

type AuthURLResult added in v0.104.0

type AuthURLResult struct {
	URL          string
	State        string
	CodeVerifier string
}

AuthURLResult holds the generated authorization URL along with the state and PKCE code verifier that must be stored in the session before redirecting.

func (AuthURLResult) GetCodeVerifier added in v0.235.0

func (a AuthURLResult) GetCodeVerifier() string

func (AuthURLResult) GetState added in v0.235.0

func (a AuthURLResult) GetState() string

func (AuthURLResult) GetURL added in v0.235.0

func (a AuthURLResult) GetURL() string

type Authenticator

type Authenticator struct {
	*oidc.Provider
	oauth2.Config
	// contains filtered or unexported fields
}

Authenticator is used to authenticate our users.

func (*Authenticator) ClearAuth added in v0.235.0

func (a *Authenticator) ClearAuth(ctx context.Context)

ClearAuth removes all authentication-related keys from the session.

func (*Authenticator) ClearState added in v0.235.0

func (a *Authenticator) ClearState(ctx context.Context)

ClearState removes all data related to an authorization exchange from the session.

func (*Authenticator) GenerateAuthURL added in v0.235.0

func (a *Authenticator) GenerateAuthURL(req *http.Request) (*AuthURLResult, error)

GenerateAuthURL constructs the Auth0 Universal Login redirect URL using PKCE.

func (*Authenticator) GenerateLogoutURL added in v0.235.0

func (a *Authenticator) GenerateLogoutURL(req *http.Request) (*url.URL, error)

GenerateLogoutURL generates URL to log the user out from the auth backend.

func (*Authenticator) GetAccessToken added in v0.235.0

func (a *Authenticator) GetAccessToken(ctx context.Context) (string, error)

func (*Authenticator) GetCodeVerifier added in v0.235.0

func (a *Authenticator) GetCodeVerifier(ctx context.Context) (string, error)

func (*Authenticator) GetRefreshToken added in v0.235.0

func (a *Authenticator) GetRefreshToken(ctx context.Context) (string, error)

func (*Authenticator) GetReturnTo added in v0.235.0

func (a *Authenticator) GetReturnTo(ctx context.Context) (string, error)

func (*Authenticator) GetState added in v0.235.0

func (a *Authenticator) GetState(ctx context.Context) (string, error)

func (*Authenticator) GetTokenExpiry added in v0.235.0

func (a *Authenticator) GetTokenExpiry(ctx context.Context) (time.Time, error)

func (*Authenticator) IsAccessTokenExpired added in v0.235.0

func (a *Authenticator) IsAccessTokenExpired(ctx context.Context) bool

IsAccessTokenExpired returns true if the access token has expired.

func (*Authenticator) IsAuthenticated added in v0.235.0

func (a *Authenticator) IsAuthenticated(ctx context.Context) bool

IsAuthenticated returns true if the session contains an access token.

func (*Authenticator) PerformExchange added in v0.235.0

func (a *Authenticator) PerformExchange(
	ctx context.Context,
	code, verifier string,
) (*models.UserProfileResponse, error)

PerformExchange handles verifying and exchanging the authorization code for an access token. It also extracts the ID token and user profile.

func (*Authenticator) PutCodeVerifier added in v0.235.0

func (a *Authenticator) PutCodeVerifier(ctx context.Context, verifier string)

func (*Authenticator) PutReturnTo added in v0.235.0

func (a *Authenticator) PutReturnTo(ctx context.Context, path string)

func (*Authenticator) PutState added in v0.235.0

func (a *Authenticator) PutState(ctx context.Context, state string)

func (*Authenticator) RefreshTokens added in v0.235.0

func (a *Authenticator) RefreshTokens(
	ctx context.Context,
	refreshToken string,
) error

RefreshTokens exchanges a refresh token for a new set of tokens.

func (*Authenticator) VerifyIDToken

func (a *Authenticator) VerifyIDToken(ctx context.Context, token *oauth2.Token) (*oidc.IDToken, string, error)

VerifyIDToken verifies that an *oauth2.Token is a valid *oidc.IDToken.

type Config

type Config struct {
	Domain       string `koanf:"domain"       validate:"required"`
	MgmtDomain   string `koanf:"mgmtdomain"   validate:"required"`
	ClientID     string `koanf:"clientid"     validate:"required"`
	ClientSecret string `koanf:"clientsecret" validate:"required"`
	CallbackURL  string `koanf:"callbackurl"  validate:"required,url"`
}

Config structure.

type Manager added in v0.240.0

type Manager struct {
	*client.Management
}

func (*Manager) ChangeUserPassword added in v0.240.0

func (m *Manager) ChangeUserPassword(ctx context.Context, request *models.ChangePasswordRequest) error

ChangeUserPassword will perform a password change on behalf of a user.

func (*Manager) DeleteUser added in v0.240.0

func (m *Manager) DeleteUser(ctx context.Context, id string) error

DeleteUser will delete the given user from the Auth0 backend.

func (*Manager) GetNewInactiveUsers added in v0.240.0

func (m *Manager) GetNewInactiveUsers(ctx context.Context) ([]*UserData, error)

GetNewInactiveUsers returns all accounts created on the backend that haven't yet logged in to the app.

func (*Manager) GetUser added in v0.240.0

func (m *Manager) GetUser(ctx context.Context, id string) (*UserData, error)

GetUser fetches the user with the given ID from Auth0.

func (*Manager) UpdateUser added in v0.240.0

func (m *Manager) UpdateUser(ctx context.Context, update *UpdateUserData) error

UpdateUser updates user data in Auth0.

func (*Manager) UpdateUserCustomisation added in v0.240.0

func (m *Manager) UpdateUserCustomisation(ctx context.Context, request *models.EditUserRequest) error

UpdateUserCustomisation writes local user customization changes back to the authorization service.

func (*Manager) UpdateUserMetadata added in v0.240.0

func (m *Manager) UpdateUserMetadata(ctx context.Context, id string, key string, value any) error

UpdateUserMetadata updates the metadata associated with a user on the backend service.

type SessionManager added in v0.235.0

type SessionManager interface {
	Get(ctx context.Context, key string) any
	Put(ctx context.Context, key string, value any)
	Remove(ctx context.Context, key string)
}

type TokenResponse added in v0.104.0

type TokenResponse struct {
	AccessToken  string `json:"access_token"`
	RefreshToken string `json:"refresh_token"`
	IDToken      string `json:"id_token"`
	TokenType    string `json:"token_type"`
	ExpiresIn    int64  `json:"expires_in"` // seconds until expiry
}

TokenResponse represents the JSON response from the Auth0 /oauth/token endpoint.

type UpdateUserData added in v0.61.0

type UpdateUserData struct {
	*management.UpdateUserRequestContent

	ID string
}

type UserData added in v0.47.0

type UserProfile

type UserProfile struct {
	// URL of the server which issued this token.
	Issuer string `json:"iss" validate:"required,url"`
	// The client ID, or set of client IDs, that this token is issued for.
	Audience string `json:"aud" validate:"required"`
	// When the token was issued by the provider.
	IssuedAt int64 `json:"iat" validate:"required"`
	// Expiry of the token.
	Expiry int64 `json:"exp" validate:"required"`
	// A unique string which identifies the end user.
	Subject string `json:"sub" validate:"required"`
	// ID of the current session.
	SessionID string `json:"sid" validate:"required"`
	// The user's email address.
	Email string `json:"email" validate:"email"`
	// Indicates whether the user has verified their email address.
	EmailVerified bool `json:"email_verified"`
	// URL pointing to the user's profile picture.
	Picture string `json:"picture" validate:"omitempty,url"`
	// The user's family name.
	FamilyName string `json:"family_name"`
	// The user's family name.
	GivenName string `json:"given_name"`
	// The user's full name.
	Name string `json:"name"`
	// The user's nickname.
	Nickname string `json:"nickname"`
	// Timestamp indicating when the user's profile was last updated/modified.
	UpdatedAt string `json:"updated_at"`
	// LoginsCount is the number of times the user has logged in. If a user is blocked and logs in, the blocked session
	// is still counted. For a new user, this will be 1 as creating the account is counted as the first login.
	LoginsCount int64 `json:"logins_count" validate:"omitempty,gt=1"`
	// Blocked indicates whether the user has been blocked. Importing enables subscribers to ensure that users remain
	// blocked when migrating to Auth0.
	Blocked bool `json:"blocked"`
	// Custom fields that store info about a user that influences the user’s access, such as support plan, security
	// roles (if not using the Authorization Core feature set), or access control groups.
	AppMetadata map[string]any `json:"app_metadata"`
}

UserProfile represents the data returned from the auth0 backend that represents an authorised user.

https://auth0.com/docs/manage-users/user-accounts/user-profiles/user-profile-structure

https://pkg.go.dev/github.com/coreos/go-oidc/v3@v3.15.0/oidc#IDToken

func (*UserProfile) GetEmail

func (u *UserProfile) GetEmail() string

GetEmail returns the email address associated with the external user.

func (*UserProfile) GetID

func (u *UserProfile) GetID() string

GetID returns a string that represents the ID of the external user.

Jump to

Keyboard shortcuts

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