Documentation
¶
Index ¶
- func ParseIDTokenUnverified(idTokenStr string) (golangjwt.MapClaims, error)
- func WillValidateAlgorithm(alg ...string) func(*Token)
- type Entitlement
- type EntitlementCondition
- type EntitlementsResult
- type FeatureFlag
- type FeatureFlagCondition
- type GetPermissionOptions
- type GetPermissionsOptions
- type HasBillingEntitlementsOptions
- type HasFeatureFlagsOptions
- type HasPermissionsOptions
- type HasRolesOptions
- type IsAuthenticatedOptions
- type Option
- func WillValidateAudience(expectedAudience string) Option
- func WillValidateClaims(f func(golangjwt.MapClaims) (bool, error)) Option
- func WillValidateIssuer(issuer string) Option
- func WillValidateWithClockSkew(leeway time.Duration) Option
- func WillValidateWithJWKSUrl(url string) Option
- func WillValidateWithKeyFunc(keyFunc func(*golangjwt.Token) (interface{}, error)) Option
- func WillValidateWithPublicKey(keyFunc func(rawToken string) (*rsa.PublicKey, error)) Option
- func WillValidateWithTimeFunc(timeFunc func() time.Time) Option
- type PermissionAccess
- type PermissionCondition
- type PermissionsWithOrg
- type Plan
- type Role
- type RoleCondition
- type Token
- func ParseFromAuthorizationHeader(r *http.Request, options ...func(*Token)) (*Token, error)
- func ParseFromSessionStorage(rawToken string, options ...func(*Token)) (*Token, error)
- func ParseFromString(rawAccessToken string, options ...func(*Token)) (*Token, error)
- func ParseOAuth2Token(rawToken *oauth2.Token, options ...func(*Token)) (*Token, error)
- func (j *Token) AsString() (string, error)
- func (j *Token) GetAccessToken() (string, bool)
- func (j *Token) GetAudience() []string
- func (j *Token) GetAuthorizedParty() string
- func (j *Token) GetClaim(key string) (interface{}, bool)
- func (j *Token) GetClaims() map[string]any
- func (j *Token) GetEntitlement(ctx context.Context, apiClient *account_api.Client, key string) (*Entitlement, error)
- func (j *Token) GetEntitlements(ctx context.Context, apiClient *account_api.Client) (*EntitlementsResult, error)
- func (j *Token) GetExpiration() (int64, bool)
- func (j *Token) GetFeatureFlag(name string) (FeatureFlag, bool)
- func (j *Token) GetFeatureFlagBool(name string) (bool, bool)
- func (j *Token) GetFeatureFlagInt(name string) (int64, bool)
- func (j *Token) GetFeatureFlagString(name string) (string, bool)
- func (j *Token) GetFeatureFlags() map[string]FeatureFlag
- func (j *Token) GetFeatureFlagsWithAPI(ctx context.Context, apiClient *account_api.Client, forceAPI bool) (map[string]FeatureFlag, error)
- func (j *Token) GetFlag(ctx context.Context, apiClient *account_api.Client, key string, forceAPI bool) (interface{}, error)
- func (j *Token) GetIdToken() (string, bool)
- func (j *Token) GetIssuedAt() (int64, bool)
- func (j *Token) GetIssuer() string
- func (j *Token) GetJWTID() string
- func (j *Token) GetOrganizationCode() string
- func (j *Token) GetPermission(ctx context.Context, apiClient *account_api.Client, permissionKey string, ...) (*PermissionAccess, error)
- func (j *Token) GetPermissions() []string
- func (j *Token) GetPermissionsWithAPI(ctx context.Context, apiClient *account_api.Client, ...) (*PermissionsWithOrg, error)
- func (j *Token) GetRawToken() *oauth2.Token
- func (j *Token) GetRefreshToken() (string, bool)
- func (j *Token) GetRoles() []Role
- func (j *Token) GetRolesWithAPI(ctx context.Context, apiClient *account_api.Client, forceAPI bool) ([]Role, error)
- func (j *Token) GetScopes() []string
- func (j *Token) GetSubject() string
- func (j *Token) GetUserOrganizations() []string
- func (j *Token) GetUserProfile() *UserProfile
- func (j *Token) GetValidationErrors() error
- func (j *Token) HasBillingEntitlements(ctx context.Context, apiClient *account_api.Client, priceNames []string, ...) (bool, error)
- func (j *Token) HasFeatureFlags(ctx context.Context, apiClient *account_api.Client, flagKeys []string, ...) (bool, error)
- func (j *Token) HasPermissions(ctx context.Context, apiClient *account_api.Client, permissionKeys []string, ...) (bool, error)
- func (j *Token) HasRoles(roleKeys ...string) bool
- func (j *Token) HasRolesWithAPI(ctx context.Context, apiClient *account_api.Client, roleKeys []string, ...) (bool, error)
- func (j *Token) IsAuthenticated(ctx context.Context, options IsAuthenticatedOptions) bool
- func (j *Token) IsTokenExpired(threshold int64) bool
- func (j *Token) IsValid() bool
- type UserProfile
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ParseIDTokenUnverified ¶ added in v0.2.0
ParseIDTokenUnverified parses an ID token without cryptographic validation.
This function should ONLY be used for ID tokens that have already been validated during the OAuth flow (e.g., tokens obtained directly from a trusted OAuth2 token exchange). It parses the JWT structure and extracts claims without verifying the signature or standard JWT claims (exp, iat, nbf, etc.).
Use cases:
- Extracting user profile information from an ID token obtained via OAuth2 code flow
- Reading organization memberships from a validated ID token
- Accessing custom claims from a trusted ID token
DO NOT use this function to parse:
- Access tokens that require validation
- ID tokens from untrusted sources
- Tokens that haven't been obtained through a secure OAuth2 flow
Parameters:
- idTokenStr: The raw JWT string to parse
Returns the parsed JWT claims as a map, or an error if parsing fails.
func WillValidateAlgorithm ¶ added in v0.0.5
WillValidateAlgorithm configures token validation to only accept tokens signed with the specified algorithm(s).
This option provides security by ensuring that only tokens signed with expected algorithms are accepted. If no algorithms are specified, it defaults to RS256 (RSA with SHA-256), which is the standard algorithm used by Kinde.
Parameters:
- alg: One or more algorithm names to accept (e.g., "RS256", "ES256"). If no algorithms are provided, defaults to ["RS256"].
Returns an Option that configures the token to validate the algorithm.
Example:
token, err := jwt.ParseFromString(tokenString,
jwt.WillValidateWithJWKSUrl("https://yourdomain.kinde.com/.well-known/jwks.json"),
jwt.WillValidateAlgorithm("RS256", "ES256"), // Accept only RS256 or ES256
)
Types ¶
type Entitlement ¶ added in v0.2.0
type Entitlement struct {
// ID is the unique identifier for this entitlement.
ID string
// FixedCharge is the fixed charge amount for this entitlement.
FixedCharge float64
// PriceName is the display name of the pricing tier or plan.
PriceName string
// UnitAmount is the per-unit charge amount for usage-based billing.
UnitAmount float64
// FeatureKey is the unique key identifying the feature this entitlement grants access to.
FeatureKey string
// FeatureName is the human-readable name of the feature.
FeatureName string
// EntitlementLimitMax is the maximum usage limit for this entitlement (0 = unlimited).
EntitlementLimitMax int
// EntitlementLimitMin is the minimum usage limit for this entitlement.
EntitlementLimitMin int
}
Entitlement represents a billing entitlement assigned to an organization. It defines access to features and their associated billing information.
type EntitlementCondition ¶ added in v0.2.0
type EntitlementCondition func(entitlement Entitlement) bool
EntitlementCondition is a function type for custom entitlement validation. It receives the entitlement and returns whether the condition is met.
type EntitlementsResult ¶ added in v0.2.0
type EntitlementsResult struct {
// OrgCode is the unique identifier for the organization.
OrgCode string
// Plans is the list of subscription plans the organization is currently subscribed to.
Plans []Plan
// Entitlements is the list of all billing entitlements granted to the organization.
Entitlements []Entitlement
}
EntitlementsResult represents the complete billing entitlements information for an organization. It includes the organization code, active subscription plans, and all entitlements.
type FeatureFlag ¶ added in v0.1.3
type FeatureFlag struct {
Type string `json:"t"`
Value interface{} `json:"v"`
}
FeatureFlag represents a single feature flag with its type and value.
type FeatureFlagCondition ¶ added in v0.2.0
type FeatureFlagCondition struct {
// Value, if set, requires the flag to have this specific value.
// If nil, only checks for existence.
Value interface{}
}
FeatureFlagCondition represents a condition for checking feature flags. It can be either a simple existence check or a value comparison.
type GetPermissionOptions ¶ added in v0.2.0
type GetPermissionOptions struct {
// ForceAPI when true, forces fetching the permission from the Account API instead of the token.
// When false, the permission is checked against the access token claims.
ForceAPI bool
}
GetPermissionOptions contains options for GetPermission.
type GetPermissionsOptions ¶ added in v0.2.0
type GetPermissionsOptions struct {
// ForceAPI when true, forces fetching permissions from the Account API instead of the token.
// When false, permissions are read from the access token claims.
ForceAPI bool
}
GetPermissionsOptions contains options for GetPermissionsWithAPI. It controls whether to fetch permissions from the Account API or the token.
type HasBillingEntitlementsOptions ¶ added in v0.2.0
type HasBillingEntitlementsOptions struct {
// CustomConditions is a map of entitlement price names to custom validation functions.
// If an entitlement has a custom condition, it will be called to validate the entitlement.
CustomConditions map[string]EntitlementCondition
}
HasBillingEntitlementsOptions contains options for HasBillingEntitlements.
type HasFeatureFlagsOptions ¶ added in v0.2.0
type HasFeatureFlagsOptions struct {
// ForceAPI when true, forces fetching feature flags from the Account API instead of the token.
ForceAPI bool
// Conditions is a map of feature flag keys to their validation conditions.
// The keys should match the feature flag keys (not display names), consistent with GetFlag().
// If a condition has a Value set, the flag must match that value.
// If Value is nil, only checks for existence.
Conditions map[string]FeatureFlagCondition
}
HasFeatureFlagsOptions contains options for HasFeatureFlags.
type HasPermissionsOptions ¶ added in v0.2.0
type HasPermissionsOptions struct {
// ForceAPI when true, forces fetching permissions from the Account API instead of the token.
ForceAPI bool
// CustomConditions is a map of permission keys to custom validation functions.
// If a permission key has a custom condition, it will be called to validate the permission.
CustomConditions map[string]PermissionCondition
}
HasPermissionsOptions contains options for HasPermissions.
type HasRolesOptions ¶ added in v0.2.0
type HasRolesOptions struct {
// ForceAPI when true, forces fetching roles from the Account API instead of the token.
ForceAPI bool
// CustomConditions is a map of role keys to custom validation functions.
// If a role key has a custom condition, it will be called to validate the role.
CustomConditions map[string]RoleCondition
}
HasRolesOptions contains options for HasRoles.
type IsAuthenticatedOptions ¶ added in v0.2.0
type IsAuthenticatedOptions struct {
// UseRefreshToken, if true, attempts to refresh the token if it's expired.
// This requires a token source that supports refresh (e.g., AuthorizationCodeFlow).
UseRefreshToken bool
// ExpiredThreshold is the threshold in seconds to consider a token expired.
// If the token will expire within this many seconds, it's considered expired.
ExpiredThreshold int64
}
IsAuthenticatedOptions contains options for checking authentication status.
type Option ¶ added in v0.0.6
type Option func(*Token)
Option is a function type that configures a Token during parsing and validation. Options are passed to parse functions (e.g., ParseFromString, ParseOAuth2Token) to customize token validation behavior, such as signature verification, claim validation, and parser settings.
func WillValidateAudience ¶
WillValidateAudience configures token validation to verify that the token's audience (aud) claim contains the expected audience value.
This option ensures that tokens were issued for the expected client/application, preventing tokens intended for other applications from being accepted. The audience is typically your Kinde client ID.
Parameters:
- expectedAudience: The expected audience string that must be present in the token's "aud" claim (which can be a single string or an array of strings).
Returns an Option that configures the token to validate the audience.
Example:
token, err := jwt.ParseFromString(tokenString,
jwt.WillValidateWithJWKSUrl("https://yourdomain.kinde.com/.well-known/jwks.json"),
jwt.WillValidateAudience("your-client-id"),
)
func WillValidateClaims ¶ added in v0.1.2
WillValidateClaims configures token validation to use a custom function for validating token claims.
This option provides maximum flexibility for claim validation, allowing you to implement any custom logic needed to validate claims beyond the standard JWT validations. The validation function receives all claims and can perform complex checks, such as validating custom claims, checking claim combinations, or implementing business logic.
Parameters:
f: A validation function that receives the token claims and returns:
bool: true if validation passes, false otherwise
error: an error describing why validation failed (if any)
If the function is nil, a validation error will be added to the token.
Returns an Option that configures the token to use the provided validation function.
Example:
token, err := jwt.ParseFromString(tokenString,
jwt.WillValidateWithJWKSUrl("https://yourdomain.kinde.com/.well-known/jwks.json"),
jwt.WillValidateClaims(func(claims jwt.MapClaims) (bool, error) {
// Validate custom claim
if role, ok := claims["role"].(string); ok {
if role != "admin" && role != "user" {
return false, fmt.Errorf("invalid role: %s", role)
}
}
return true, nil
}),
)
func WillValidateIssuer ¶ added in v0.0.3
WillValidateIssuer configures token validation to verify that the token's issuer (iss) claim matches the expected issuer.
This option ensures that tokens were issued by the expected authorization server, preventing tokens from other issuers from being accepted. The issuer is typically your Kinde domain URL (e.g., "https://yourdomain.kinde.com").
Parameters:
- issuer: The expected issuer string that must match the token's "iss" claim.
Returns an Option that configures the token to validate the issuer.
Example:
token, err := jwt.ParseFromString(tokenString,
jwt.WillValidateWithJWKSUrl("https://yourdomain.kinde.com/.well-known/jwks.json"),
jwt.WillValidateIssuer("https://yourdomain.kinde.com"),
)
func WillValidateWithClockSkew ¶
WillValidateWithClockSkew configures token validation to allow a time leeway (clock skew) when validating expiration and issued-at claims.
This option is useful when there are small time differences between the token issuer's clock and your server's clock. The leeway is applied to both expiration and issued-at validation, allowing tokens to be accepted slightly before or after their exact expiration time.
Parameters:
- leeway: The maximum time difference allowed (e.g., 5*time.Minute). Positive values allow tokens to be accepted slightly after expiration or before issuance.
Returns an Option that configures the token to use the specified clock skew.
Example:
token, err := jwt.ParseFromString(tokenString,
jwt.WillValidateWithJWKSUrl("https://yourdomain.kinde.com/.well-known/jwks.json"),
jwt.WillValidateWithClockSkew(5*time.Minute), // Allow 5 minute clock skew
)
func WillValidateWithJWKSUrl ¶
WillValidateWithJWKSUrl configures token validation to use a JSON Web Key Set (JWKS) endpoint for automatic signature verification.
This option fetches public keys from the specified JWKS URL and automatically selects the appropriate key based on the token's "kid" (key ID) claim. The JWKS client handles caching and automatic key refresh.
This is the recommended approach for validating tokens issued by Kinde, as it automatically handles key rotation and key discovery.
Parameters:
- url: The JWKS endpoint URL (e.g., "https://yourdomain.kinde.com/.well-known/jwks.json")
Returns an Option that configures the token to use the JWKS endpoint for validation. If the JWKS client cannot be created, the option will add a validation error to the token.
Example:
token, err := jwt.ParseFromString(tokenString,
jwt.WillValidateWithJWKSUrl("https://yourdomain.kinde.com/.well-known/jwks.json"),
)
func WillValidateWithKeyFunc ¶
WillValidateWithKeyFunc configures token validation to use a custom key function that returns the cryptographic key for signature verification.
This option provides maximum flexibility for key retrieval, allowing you to implement any custom logic needed to determine which key to use for validation. The key function receives the parsed JWT token and can inspect its claims (e.g., "kid", "alg") to select the appropriate key.
Parameters:
- keyFunc: A function that receives the parsed JWT token and returns the cryptographic key (interface{} to support various key types) or an error if the key cannot be retrieved.
Returns an Option that configures the token to use the provided key function.
Example:
token, err := jwt.ParseFromString(tokenString,
jwt.WillValidateWithKeyFunc(func(t *jwt.Token) (interface{}, error) {
kid, _ := t.Header["kid"].(string)
return getKeyByKid(kid)
}),
)
func WillValidateWithPublicKey ¶
WillValidateWithPublicKey configures token validation to use a custom function that retrieves an RSA public key for signature verification.
This option is useful when you have a custom key retrieval mechanism or when you need to extract key information from the token itself (e.g., from a "kid" claim) to determine which key to use.
Parameters:
- keyFunc: A function that receives the raw token string and returns the RSA public key to use for signature verification, or an error if the key cannot be retrieved.
Returns an Option that configures the token to use the provided key function.
Example:
token, err := jwt.ParseFromString(tokenString,
jwt.WillValidateWithPublicKey(func(rawToken string) (*rsa.PublicKey, error) {
// Extract key ID from token and return corresponding public key
return getPublicKeyFromToken(rawToken)
}),
)
func WillValidateWithTimeFunc ¶
WillValidateWithTimeFunc configures token validation to use a custom time function instead of the current system time.
This option is primarily useful for testing, allowing you to control the "current" time used for expiration and issued-at claim validation. It can also be used to handle clock synchronization issues in production.
Parameters:
- timeFunc: A function that returns the time to use as the "current" time for validation. Typically returns time.Now() in production, but can return a fixed time for testing.
Returns an Option that configures the token to use the provided time function.
Example:
// For testing with a fixed time
fixedTime := time.Date(2024, 1, 1, 12, 0, 0, 0, time.UTC)
token, err := jwt.ParseFromString(tokenString,
jwt.WillValidateWithTimeFunc(func() time.Time { return fixedTime }),
)
type PermissionAccess ¶ added in v0.2.0
type PermissionAccess struct {
// PermissionKey is the key of the permission being checked.
PermissionKey string
// OrgCode is the organization code associated with the permission, or empty if not applicable.
OrgCode string
// IsGranted indicates whether the user has been granted this permission.
IsGranted bool
}
PermissionAccess represents the access status for a specific permission. It contains the permission key, organization code, and whether the permission is granted.
type PermissionCondition ¶ added in v0.2.0
PermissionCondition is a function type for custom permission validation. It receives the permission key and organization code, and returns whether the condition is met.
type PermissionsWithOrg ¶ added in v0.2.0
type PermissionsWithOrg struct {
// OrgCode is the unique identifier for the organization.
OrgCode string
// Permissions is a list of permission strings (e.g., "read:users", "write:posts")
// that the user has been granted within the organization.
Permissions []string
}
PermissionsWithOrg represents permissions associated with an organization. It contains both the organization code and the list of permission strings that the user has within that organization.
type Plan ¶ added in v0.2.0
type Plan struct {
// Key is the unique identifier for the subscription plan.
Key string
// SubscribedOn is the ISO 8601 timestamp when the organization subscribed to this plan.
SubscribedOn string
}
Plan represents a subscription plan that an organization is subscribed to.
type RoleCondition ¶ added in v0.2.0
RoleCondition is a function type for custom role validation. It receives the role and returns whether the condition is met.
type Token ¶
type Token struct {
// contains filtered or unexported fields
}
Token represents a JWT token.
func ParseFromAuthorizationHeader ¶
ParseFromAuthorizationHeader extracts and parses a JWT token from the HTTP Authorization header.
The function expects the Authorization header to be in the format "Bearer <token>". It extracts the token string, creates an OAuth2 token, and parses it with the provided options.
Parameters:
- r: The HTTP request containing the Authorization header
- options: Optional configuration functions for token parsing and validation (e.g., WillValidateWithJWKSUrl, WillValidateIssuer, WillValidateAudience)
Returns a parsed and validated Token, or an error if:
- The Authorization header is missing or malformed
- The token format is invalid (not "Bearer <token>")
- Token parsing or validation fails
Example:
token, err := jwt.ParseFromAuthorizationHeader(r,
jwt.WillValidateWithJWKSUrl("https://yourdomain.kinde.com/.well-known/jwks.json"),
jwt.WillValidateIssuer("https://yourdomain.kinde.com"),
)
func ParseFromSessionStorage ¶
ParseFromSessionStorage parses a JWT token from a JSON string stored in session storage.
This function is designed to reconstruct an OAuth2 token from a JSON-encoded string that was previously stored (e.g., in a session cookie or database). It unmarshals the JSON string to extract both the standard OAuth2 token fields and any extra fields (such as id_token) that may have been stored.
Parameters:
- rawToken: A JSON-encoded string representation of an oauth2.Token
- options: Optional configuration functions for token parsing and validation (e.g., WillValidateWithJWKSUrl, WillValidateIssuer, WillValidateAudience)
Returns a parsed and validated Token, or an error if:
- The JSON string is malformed
- Token parsing or validation fails
Example:
// Token was stored as JSON string in session
tokenJSON := `{"access_token":"...","token_type":"Bearer","id_token":"..."}`
token, err := jwt.ParseFromSessionStorage(tokenJSON,
jwt.WillValidateWithJWKSUrl("https://yourdomain.kinde.com/.well-known/jwks.json"),
)
func ParseFromString ¶
ParseFromString parses a raw JWT access token string and validates it with the given options.
This is a convenience function that wraps a raw token string in an OAuth2 token structure and parses it. Use this when you have the token as a string and want to validate it.
Parameters:
- rawAccessToken: The raw JWT access token string to parse
- options: Optional configuration functions for token parsing and validation (e.g., WillValidateWithJWKSUrl, WillValidateIssuer, WillValidateAudience)
Returns a parsed and validated Token, or an error if token parsing or validation fails.
Example:
token, err := jwt.ParseFromString(accessTokenString,
jwt.WillValidateWithJWKSUrl("https://yourdomain.kinde.com/.well-known/jwks.json"),
)
func ParseOAuth2Token ¶
ParseOAuth2Token parses and validates an OAuth2 token with the given options.
This is the core parsing function that all other parse functions ultimately call. It extracts the access token from the OAuth2 token structure, applies configuration options (such as key functions, validation rules, and parser settings), and performs JWT parsing and validation.
The function supports various validation options:
- Signature verification via JWKS URL or public key
- Issuer validation
- Audience validation
- Custom claim validation
- Algorithm validation
- Clock skew tolerance
Parameters:
- rawToken: The OAuth2 token containing the access token and optional extra fields (e.g., id_token)
- options: Optional configuration functions for token parsing and validation (e.g., WillValidateWithJWKSUrl, WillValidateIssuer, WillValidateAudience, WillValidateClaims)
Returns a Token with validation results. The Token will contain:
- The parsed JWT claims (accessible via GetClaims, GetSubject, etc.)
- Validation status (checkable via IsValid)
- Any validation errors (accessible via GetValidationErrors)
Even if validation fails, a Token is returned (with isValid=false) along with an error containing details about what failed. This allows callers to inspect the token and errors.
Example:
oauth2Token := &oauth2.Token{AccessToken: "eyJhbGc..."}
token, err := jwt.ParseOAuth2Token(oauth2Token,
jwt.WillValidateWithJWKSUrl("https://yourdomain.kinde.com/.well-known/jwks.json"),
jwt.WillValidateIssuer("https://yourdomain.kinde.com"),
jwt.WillValidateAudience("your-client-id"),
)
func (*Token) AsString ¶
AsString serializes the underlying OAuth2 token to a JSON string.
This is useful for storing the token in session storage or transmitting it as a string. The resulting JSON can be parsed back using ParseFromSessionStorage().
Returns the JSON-encoded token string, or an error if JSON marshaling fails.
func (*Token) GetAccessToken ¶ added in v0.0.3
GetAccessToken returns the access token string from the OAuth2 token.
The access token is the JWT that was parsed and validated. It can be used to make authenticated API requests to protected resources.
Returns the access token string and true if the access token exists, or empty string and false if the token is not available.
func (*Token) GetAudience ¶ added in v0.1.3
GetAudience returns the audience (aud) claim from the JWT token.
The audience claim identifies the recipients that the JWT is intended for, typically the client ID. This is a standard JWT claim defined in RFC 7519. The claim can be either a single string or an array of strings.
Returns a slice of audience strings, or nil if the claim is not present or the token was not parsed successfully.
func (*Token) GetAuthorizedParty ¶ added in v0.1.3
GetAuthorizedParty returns the authorized party (azp) claim from the JWT token.
The authorized party claim identifies the party to which the JWT was issued. This is typically the client ID that requested the token. This claim is defined in the OpenID Connect specification.
Returns the authorized party string, or an empty string if the claim is not present or the token was not parsed successfully.
func (*Token) GetClaim ¶ added in v0.2.0
GetClaim retrieves a specific claim value from the token by key.
This method provides direct access to any claim in the JWT, including both standard claims (sub, iss, aud, exp, etc.) and custom claims. The returned value is an interface{} that may need type assertion based on the expected claim type.
Parameters:
- key: The claim key to retrieve (e.g., "sub", "permissions", "custom_claim")
Returns the claim value and true if the claim exists, or nil and false if the claim is not present or the token was not parsed successfully.
func (*Token) GetClaims ¶ added in v0.0.7
GetClaims returns all claims from the JWT token as a map.
This method provides direct access to the entire claims map, allowing you to inspect all claims in the token, including standard JWT claims and any custom claims that were included.
Returns a map of all claims, or an empty map if the token was not parsed successfully. The map keys are claim names (strings) and values are the claim values (interface{}).
func (*Token) GetEntitlement ¶ added in v0.2.0
func (j *Token) GetEntitlement(ctx context.Context, apiClient *account_api.Client, key string) (*Entitlement, error)
GetEntitlement fetches a single billing entitlement by key from the Kinde Account API.
Note: Entitlements are always fetched from the API and are never included in the token, as they contain sensitive billing information that may change frequently.
Parameters:
- ctx: Context for the API request
- apiClient: The Account API client for making authenticated requests
- key: The entitlement key to fetch
Returns Entitlement containing the entitlement details, or an error if the API request fails.
func (*Token) GetEntitlements ¶ added in v0.2.0
func (j *Token) GetEntitlements(ctx context.Context, apiClient *account_api.Client) (*EntitlementsResult, error)
GetEntitlements fetches billing entitlements from the Kinde Account API.
Note: Entitlements are always fetched from the API and are never included in the token, as they contain sensitive billing information that may change frequently.
The method automatically handles pagination to retrieve all entitlements if there are multiple pages of results.
Parameters:
- ctx: Context for the API request
- apiClient: The Account API client for making authenticated requests
Returns EntitlementsResult containing the organization code, active plans, and all entitlements, or an error if the API request fails.
func (*Token) GetExpiration ¶ added in v0.1.3
GetExpiration returns the expiration time (exp) claim from the JWT token.
The expiration time claim identifies the time after which the JWT must not be accepted for processing, represented as a Unix timestamp (seconds since epoch). This is a standard JWT claim defined in RFC 7519.
Returns the expiration timestamp and true if the claim exists, or 0 and false if the claim is not present or the token was not parsed successfully.
func (*Token) GetFeatureFlag ¶ added in v0.1.3
func (j *Token) GetFeatureFlag(name string) (FeatureFlag, bool)
GetFeatureFlag retrieves a specific feature flag by its name/code.
Feature flags are used to enable or disable features for specific users or organizations. This method looks up a flag by its key in the feature_flags claim.
Parameters:
- name: The feature flag code/name to retrieve
Returns the FeatureFlag and true if the flag exists, or an empty FeatureFlag and false if the flag is not present in the token.
func (*Token) GetFeatureFlagBool ¶ added in v0.1.3
GetFeatureFlagBool retrieves a boolean feature flag value by name.
This is a convenience method that retrieves a feature flag and type-checks that it is a boolean (type "b"). If the flag exists and is a boolean, it returns the boolean value.
Parameters:
- name: The feature flag code/name to retrieve
Returns the boolean value and true if the flag exists and is a boolean type, or false and false if the flag doesn't exist or is not a boolean.
func (*Token) GetFeatureFlagInt ¶ added in v0.1.3
GetFeatureFlagInt retrieves an integer feature flag value by name.
This is a convenience method that retrieves a feature flag and type-checks that it is an integer (type "i"). If the flag exists and is an integer, it returns the integer value. The method handles int, int64, and float64 types (converting float64 to int64).
Parameters:
- name: The feature flag code/name to retrieve
Returns the integer value and true if the flag exists and is an integer type, or 0 and false if the flag doesn't exist or is not an integer.
func (*Token) GetFeatureFlagString ¶ added in v0.1.3
GetFeatureFlagString retrieves a string feature flag value by name.
This is a convenience method that retrieves a feature flag and type-checks that it is a string (type "s"). If the flag exists and is a string, it returns the string value.
Parameters:
- name: The feature flag code/name to retrieve
Returns the string value and true if the flag exists and is a string type, or empty string and false if the flag doesn't exist or is not a string.
func (*Token) GetFeatureFlags ¶ added in v0.1.3
func (j *Token) GetFeatureFlags() map[string]FeatureFlag
GetFeatureFlags returns the feature_flags claim of the token. The feature flags use short codes: t=type, v=value, b=boolean, i=integer, s=string Supports both standard "feature_flags" and Hasura "x-hasura-feature-flags" claim formats.
func (*Token) GetFeatureFlagsWithAPI ¶ added in v0.2.0
func (j *Token) GetFeatureFlagsWithAPI(ctx context.Context, apiClient *account_api.Client, forceAPI bool) (map[string]FeatureFlag, error)
GetFeatureFlagsWithAPI retrieves feature flags either from the access token or the Account API.
If forceAPI is false, feature flags are extracted from the access token's claims, supporting both standard "feature_flags" and Hasura "x-hasura-feature-flags" claim formats.
If forceAPI is true, feature flags are fetched from the Kinde Account API with automatic pagination support, ensuring the most up-to-date feature flag data.
The method returns a map of feature flag codes to FeatureFlag objects, each containing the flag's code, type, and value.
Parameters:
- ctx: Context for the API request (only used when forceAPI is true)
- apiClient: The Account API client for making requests (only used when forceAPI is true)
- forceAPI: When true, forces fetching from the Account API instead of the token
Returns an error if the API request fails (when forceAPI is true).
func (*Token) GetFlag ¶ added in v0.2.0
func (j *Token) GetFlag(ctx context.Context, apiClient *account_api.Client, key string, forceAPI bool) (interface{}, error)
GetFlag retrieves a specific feature flag by key.
If forceAPI is false, the feature flag is extracted from the access token's claims, supporting both standard "feature_flags" and Hasura "x-hasura-feature-flags" claim formats. The parameter should be the feature flag key (not the display name).
If forceAPI is true, the feature flag is fetched from the Kinde Account API, ensuring the most up-to-date feature flag data. The parameter should be the feature flag key (matching the "key" field from the API response, not the "name" field).
Note: For consistency, both token and API lookups use the feature flag key. The key is the unique identifier used in tokens, while "name" is the human-readable display name.
Parameters:
- ctx: Context for the API request (only used when forceAPI is true)
- apiClient: The Account API client for making requests (only used when forceAPI is true)
- key: The key of the feature flag to retrieve (not the display name)
- forceAPI: When true, forces fetching from the Account API instead of the token
Returns the feature flag value (which can be string, boolean, number, or object), or nil if the flag is not found. Returns an error if the API request fails (when forceAPI is true).
func (*Token) GetIdToken ¶ added in v0.0.3
GetIdToken returns the ID token string if it exists in the OAuth2 token.
The ID token is typically included in the OAuth2 token's extra fields during the authorization code flow. It contains user identity information and can be used to extract user profile data via GetUserProfile().
Returns the ID token string and true if the ID token exists, or empty string and false if it is not present in the token.
func (*Token) GetIssuedAt ¶ added in v0.1.3
GetIssuedAt returns the issued at (iat) claim from the JWT token.
The issued at claim identifies the time at which the JWT was issued, represented as a Unix timestamp (seconds since epoch). This is a standard JWT claim defined in RFC 7519.
Returns the issued at timestamp and true if the claim exists, or 0 and false if the claim is not present or the token was not parsed successfully.
func (*Token) GetIssuer ¶ added in v0.1.3
GetIssuer returns the issuer (iss) claim from the JWT token.
The issuer claim identifies the principal that issued the JWT, typically the authorization server URL (e.g., "https://yourdomain.kinde.com"). This is a standard JWT claim defined in RFC 7519.
Returns the issuer string, or an empty string if the claim is not present or the token was not parsed successfully.
func (*Token) GetJWTID ¶ added in v0.1.3
GetJWTID returns the JWT ID (jti) claim from the token.
The JWT ID claim provides a unique identifier for the JWT, which can be used to prevent token replay attacks. This is a standard JWT claim defined in RFC 7519.
Returns the JWT ID string, or an empty string if the claim is not present or the token was not parsed successfully.
func (*Token) GetOrganizationCode ¶ added in v0.1.3
GetOrganizationCode returns the org_code claim of the token. Supports both standard "org_code" and Hasura "x-hasura-org-code" claim formats.
func (*Token) GetPermission ¶ added in v0.2.0
func (j *Token) GetPermission(ctx context.Context, apiClient *account_api.Client, permissionKey string, options GetPermissionOptions) (*PermissionAccess, error)
GetPermission checks if a specific permission is granted to the user.
If options.ForceAPI is false, the permission is checked against the access token's claims, which is faster but may not reflect the most recent permission changes.
If options.ForceAPI is true, the permission is fetched from the Kinde Account API, ensuring the most up-to-date permission data.
Parameters:
- ctx: Context for the API request (only used when ForceAPI is true)
- apiClient: The Account API client for making requests (only used when ForceAPI is true)
- permissionKey: The key of the permission to check (e.g., "read:users", "write:posts")
- options: Configuration options controlling the fetch behavior
Returns PermissionAccess containing the permission key, organization code, and grant status, or an error if the API request fails (when ForceAPI is true).
func (*Token) GetPermissions ¶ added in v0.1.3
GetPermissions returns the permissions claim of the token. Supports both standard "permissions" and Hasura "x-hasura-permissions" claim formats.
func (*Token) GetPermissionsWithAPI ¶ added in v0.2.0
func (j *Token) GetPermissionsWithAPI(ctx context.Context, apiClient *account_api.Client, options GetPermissionsOptions) (*PermissionsWithOrg, error)
GetPermissionsWithAPI retrieves user permissions either from the access token or the Account API.
If options.ForceAPI is false, permissions are extracted from the access token's claims, which is faster but may not reflect the most recent permission changes.
If options.ForceAPI is true, permissions are fetched from the Kinde Account API with automatic pagination support, ensuring the most up-to-date permission data.
The method returns a PermissionsWithOrg structure containing both the organization code and the list of permission strings.
Parameters:
- ctx: Context for the API request (only used when ForceAPI is true)
- apiClient: The Account API client for making requests (only used when ForceAPI is true)
- options: Configuration options controlling the fetch behavior
Returns an error if the API request fails (when ForceAPI is true).
func (*Token) GetRawToken ¶
GetRawToken returns the underlying OAuth2 token structure.
This provides access to the original OAuth2 token that was parsed, including the access token, refresh token (if available), expiration time, and any extra fields such as the ID token.
Returns the raw OAuth2 token, or nil if the token was not initialized.
func (*Token) GetRefreshToken ¶ added in v0.0.3
GetRefreshToken returns the refresh token string if it exists in the OAuth2 token.
The refresh token can be used to obtain a new access token when the current access token expires, without requiring the user to re-authenticate.
Returns the refresh token string and true if a refresh token exists, or empty string and false if no refresh token is available.
func (*Token) GetRoles ¶ added in v0.2.0
GetRoles returns the roles claim of the token. Supports both standard "roles" and Hasura "x-hasura-roles" claim formats. Returns an empty slice if no roles are found.
func (*Token) GetRolesWithAPI ¶ added in v0.2.0
func (j *Token) GetRolesWithAPI(ctx context.Context, apiClient *account_api.Client, forceAPI bool) ([]Role, error)
GetRolesWithAPI retrieves user roles either from the access token or the Account API.
If forceAPI is false, roles are extracted from the access token's claims, supporting both standard "roles" and Hasura "x-hasura-roles" claim formats.
If forceAPI is true, roles are fetched from the Kinde Account API with automatic pagination support, ensuring the most up-to-date role data.
The method returns a slice of Role objects, each containing the role's key and name.
Parameters:
- ctx: Context for the API request (only used when forceAPI is true)
- apiClient: The Account API client for making requests (only used when forceAPI is true)
- forceAPI: When true, forces fetching from the Account API instead of the token
Returns an error if the API request fails (when forceAPI is true).
func (*Token) GetScopes ¶ added in v0.1.3
GetScopes returns the scope (scp) claim from the JWT token.
The scope claim contains the OAuth2 scopes granted to the token, which define the permissions and access rights. Scopes are typically space-separated strings in OAuth2, but in JWT they are often represented as arrays.
Returns a slice of scope strings, or nil if the claim is not present or the token was not parsed successfully.
func (*Token) GetSubject ¶
GetSubject returns the subject (sub) claim from the JWT token.
The subject claim identifies the principal that the token is about, typically the user ID. This is a standard JWT claim defined in RFC 7519.
Returns the subject string, or an empty string if the claim is not present or the token was not parsed successfully.
func (*Token) GetUserOrganizations ¶ added in v0.2.0
GetUserOrganizations returns all organization codes that the user belongs to.
The method parses the ID token without validation since the token has already been validated as part of the OAuth flow. It looks for organization codes in two possible claim formats:
- "org_codes" - Standard Kinde claim format (checked first)
- "x-hasura-org-codes" - Hasura integration format (fallback)
The organization codes are extracted from whichever claim is present, and returned as a slice of strings. Each string represents a unique organization identifier.
Returns nil if:
- The ID token is not available in the OAuth2 token
- The ID token cannot be parsed
- Neither org_codes nor x-hasura-org-codes claims are present
Returns a string slice containing organization codes otherwise.
func (*Token) GetUserProfile ¶ added in v0.2.0
func (j *Token) GetUserProfile() *UserProfile
GetUserProfile extracts user profile information from the ID token.
The method parses the ID token without validation since the token has already been validated as part of the OAuth flow. It extracts standard OpenID Connect claims including the subject (user ID), given name, family name, email, and picture URL.
The subject (sub) claim is required - if it's missing or empty, the method returns nil. All other profile fields are optional and will be empty strings if not present in the token.
Returns nil if:
- The ID token is not available in the OAuth2 token
- The ID token cannot be parsed
- The subject (sub) claim is missing or empty
Returns a UserProfile pointer containing the extracted profile information otherwise.
func (*Token) GetValidationErrors ¶ added in v0.0.3
GetValidationErrors returns an aggregated error containing all validation errors that occurred during token parsing and validation.
If the token was parsed and validated successfully, this method returns nil. If validation failed, it returns an error that aggregates all validation failures, which may include:
- Signature verification failures
- Expired token errors
- Invalid issuer errors
- Invalid audience errors
- Custom claim validation failures
- Algorithm mismatch errors
Use this method to get detailed information about why a token validation failed, especially when IsValid() returns false.
Returns nil if there are no validation errors, or an aggregated error containing all validation failures.
func (*Token) HasBillingEntitlements ¶ added in v0.2.0
func (j *Token) HasBillingEntitlements(ctx context.Context, apiClient *account_api.Client, priceNames []string, options HasBillingEntitlementsOptions) (bool, error)
HasBillingEntitlements checks if the organization has all of the specified billing entitlements.
Note: Entitlements are always fetched from the API and are never included in the token, as they contain sensitive billing information that may change frequently.
Custom conditions can be provided for each entitlement to perform additional validation beyond simple existence checks (e.g., checking limits, usage, custom business logic).
Parameters:
- ctx: Context for the API request
- apiClient: The Account API client for making authenticated requests
- priceNames: The list of entitlement price names to check
- options: Configuration options controlling the check behavior
Returns true if all entitlements exist (and pass custom conditions if provided), false otherwise. Returns an error if the API request fails.
func (*Token) HasFeatureFlags ¶ added in v0.2.0
func (j *Token) HasFeatureFlags(ctx context.Context, apiClient *account_api.Client, flagKeys []string, options HasFeatureFlagsOptions) (bool, error)
HasFeatureFlags checks if the user has all of the specified feature flags.
If options.ForceAPI is false, feature flags are checked against the access token's claims. If options.ForceAPI is true, feature flags are fetched from the Kinde Account API.
Conditions can be provided for each flag to check for specific values (e.g., flag must equal "enabled" or a specific number).
Note: The parameter should be feature flag keys (not display names), consistent with GetFlag(). The key is the unique identifier used in tokens, while "name" is the human-readable display name.
Parameters:
- ctx: Context for the API request (only used when ForceAPI is true)
- apiClient: The Account API client for making requests (only used when ForceAPI is true)
- flagKeys: The list of feature flag keys to check (not display names)
- options: Configuration options controlling the check behavior
Returns true if all flags exist (and match their conditions if provided), false otherwise. Returns an error if the API request fails (when ForceAPI is true).
func (*Token) HasPermissions ¶ added in v0.2.0
func (j *Token) HasPermissions(ctx context.Context, apiClient *account_api.Client, permissionKeys []string, options HasPermissionsOptions) (bool, error)
HasPermissions checks if the user has all of the specified permissions.
If options.ForceAPI is false, permissions are checked against the access token's claims. If options.ForceAPI is true, permissions are fetched from the Kinde Account API.
Custom conditions can be provided for each permission to perform additional validation beyond simple existence checks (e.g., checking organization context, custom business logic).
Parameters:
- ctx: Context for the API request (only used when ForceAPI is true)
- apiClient: The Account API client for making requests (only used when ForceAPI is true)
- permissionKeys: The list of permission keys to check
- options: Configuration options controlling the check behavior
Returns true if all permissions are granted (and pass custom conditions if provided), false otherwise. Returns an error if the API request fails (when ForceAPI is true).
func (*Token) HasRoles ¶ added in v0.2.0
HasRoles checks if the token contains any of the specified roles. Returns true if the user has at least one of the provided role keys.
func (*Token) HasRolesWithAPI ¶ added in v0.2.0
func (j *Token) HasRolesWithAPI(ctx context.Context, apiClient *account_api.Client, roleKeys []string, options HasRolesOptions) (bool, error)
HasRolesWithAPI checks if the user has all of the specified roles.
If options.ForceAPI is false, roles are checked against the access token's claims. If options.ForceAPI is true, roles are fetched from the Kinde Account API.
Custom conditions can be provided for each role to perform additional validation beyond simple existence checks (e.g., checking role properties, custom business logic).
This is an enhanced version of HasRoles that supports API fetching and custom conditions. Use the simpler HasRoles() method if you only need basic token-based role checking.
Parameters:
- ctx: Context for the API request (only used when ForceAPI is true)
- apiClient: The Account API client for making requests (only used when ForceAPI is true)
- roleKeys: The list of role keys to check
- options: Configuration options controlling the check behavior
Returns true if all roles are present (and pass custom conditions if provided), false otherwise. Returns an error if the API request fails (when ForceAPI is true).
func (*Token) IsAuthenticated ¶ added in v0.2.0
func (j *Token) IsAuthenticated(ctx context.Context, options IsAuthenticatedOptions) bool
IsAuthenticated checks if the user is authenticated based on the token.
If UseRefreshToken is true and the token is expired, this method will attempt to refresh the token using the provided token source. This is useful for automatically refreshing tokens before they expire.
Note: This method requires a token source that supports refresh (e.g., from AuthorizationCodeFlow). If UseRefreshToken is true but no refresh mechanism is available, it will only check if the token is currently valid.
Parameters:
- ctx: Context for the request (used for token refresh if needed)
- options: Configuration options for the authentication check
Returns true if the user is authenticated (token is valid or was successfully refreshed), false otherwise.
func (*Token) IsTokenExpired ¶ added in v0.2.0
IsTokenExpired checks if the token is expired, optionally considering a threshold.
The threshold parameter allows you to consider a token expired before its actual expiration time. This is useful for refreshing tokens proactively to avoid expiration during API calls.
Parameters:
- threshold: Optional threshold in seconds. If provided, the token is considered expired if it will expire within this many seconds. Defaults to 0 (only check actual expiration).
Returns true if the token is expired (or will expire within the threshold), false otherwise. Returns true if the expiration claim is missing or invalid.
func (*Token) IsValid ¶
IsValid returns whether the token passed all validation checks.
A token is considered valid if:
- It was successfully parsed as a JWT
- All signature verification checks passed
- All configured validation functions returned true
- No validation errors occurred
Returns true if the token is valid, false otherwise. For detailed error information, use GetValidationErrors().
type UserProfile ¶ added in v0.2.0
type UserProfile struct {
// ID is the unique identifier for the user (from the "sub" claim).
// This is the primary key that should be used to identify the user in your application.
ID string
// GivenName is the user's first name or given name (from the "given_name" claim).
GivenName string
// FamilyName is the user's last name or family name (from the "family_name" claim).
FamilyName string
// Email is the user's email address (from the "email" claim).
Email string
// Picture is the URL to the user's profile picture (from the "picture" claim).
Picture string
}
UserProfile represents user profile information extracted from the ID token. It contains the core user identity and profile claims defined in the OpenID Connect specification.