Documentation
¶
Index ¶
- func ExampleCustomMiddleware(next http.Handler) http.Handler
- func ExampleMiddlewareUsage()
- func TokenFromContext(ctx context.Context) (*jwt.Token, bool)
- type AuthorizationCodeFlow
- func (flow *AuthorizationCodeFlow) AuthorizationCodeReceivedHandler(w http.ResponseWriter, r *http.Request)
- func (flow *AuthorizationCodeFlow) ExchangeCode(ctx context.Context, authorizationCode string, receivedState string) error
- func (flow *AuthorizationCodeFlow) ExchangeDeviceAccessToken(ctx context.Context, da *oauth2.DeviceAuthResponse, ...) error
- func (flow *AuthorizationCodeFlow) GetAccountAPIClient(ctx context.Context) (*account_api.Client, error)
- func (flow *AuthorizationCodeFlow) GetAuthURL() string
- func (flow *AuthorizationCodeFlow) GetAuthURLWithInvitation(invitationCode string) string
- func (flow *AuthorizationCodeFlow) GetClient(ctx context.Context) (*http.Client, error)
- func (flow *AuthorizationCodeFlow) GetToken(ctx context.Context) (*jwt.Token, error)
- func (flow *AuthorizationCodeFlow) InjectTokenMiddleware(next http.Handler) http.Handler
- func (flow *AuthorizationCodeFlow) IsAuthenticated(ctx context.Context) (bool, error)
- func (flow *AuthorizationCodeFlow) Logout() error
- func (flow *AuthorizationCodeFlow) StartDeviceAuth(ctx context.Context) (*oauth2.DeviceAuthResponse, error)
- type IAuthorizationCodeFlow
- type IDeviceAuthorizationFlow
- type ISessionHooks
- type Option
- func WithAdditionalScope(scope string) Option
- func WithAudience(audience string) Option
- func WithAuthParameter(name, value string) Option
- func WithClientID(clientID string) Option
- func WithClientSecret(clientSecret string) Option
- func WithCustomStateGenerator(stateFunc func(*AuthorizationCodeFlow) string) Option
- func WithInvitationCode(invitationCode string) Option
- func WithOffline() Option
- func WithPKCE() Option
- func WithPKCEChallengeMethod(method string) Option
- func WithPrompt(prompt string) Option
- func WithReauthState(reauthState string) Option
- func WithScopes(scopes ...string) Option
- func WithSessionHooks(sessionHooks ISessionHooks) Option
- func WithSupportsReauth(supportsReauth bool) Option
- func WithTokenValidation(isValidateJWKS bool, tokenOptions ...func(*jwt.Token)) Option
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ExampleCustomMiddleware ¶ added in v0.1.3
ExampleCustomMiddleware demonstrates how to create custom middleware that uses the Kinde token.
This example shows how to build custom middleware that:
- Extracts the token from the request context (set by Kinde middleware)
- Performs custom authorization checks (e.g., scope validation)
- Handles unauthorized/forbidden cases
- Passes control to the next handler if authorized
This is a code example and should not be called directly in production code.
Parameters:
- next: The next HTTP handler in the middleware chain
Returns an HTTP handler that wraps the next handler with custom authorization logic.
func ExampleMiddlewareUsage ¶ added in v0.1.3
func ExampleMiddlewareUsage()
ExampleMiddlewareUsage demonstrates how to use the Kinde authentication middleware.
This example shows the basic pattern for integrating Kinde authentication into an HTTP application:
- Create an authorization flow
- Extract tokens from request context in handlers
- Use middleware to protect routes
This is a code example and should not be called directly in production code.
func TokenFromContext ¶ added in v0.1.3
TokenFromContext extracts the Kinde JWT token from the request context.
This helper function retrieves the parsed and validated JWT token that was previously stored in the request context by middleware (e.g., InjectTokenMiddleware). It provides a convenient way for downstream handlers to access the authenticated user's token.
Parameters:
- ctx: The request context that may contain a Kinde token
Returns the JWT token and true if a token was found in the context, or nil and false otherwise.
Example:
func myHandler(w http.ResponseWriter, r *http.Request) {
token, ok := TokenFromContext(r.Context())
if !ok {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
userID := token.GetSubject()
// Use token...
}
Types ¶
type AuthorizationCodeFlow ¶
type AuthorizationCodeFlow struct {
JWKS_URL string
// contains filtered or unexported fields
}
AuthorizationCodeFlow represents the authorization code flow.
func (*AuthorizationCodeFlow) AuthorizationCodeReceivedHandler ¶ added in v0.0.5
func (flow *AuthorizationCodeFlow) AuthorizationCodeReceivedHandler(w http.ResponseWriter, r *http.Request)
AuthorizationCodeReceivedHandler handles the OAuth2 callback from the authorization server.
This method processes the authorization callback, validates the state parameter to prevent CSRF attacks, exchanges the authorization code for tokens, and stores the tokens using the configured session hooks.
The handler expects the callback request to contain:
- "code": The authorization code from the authorization server
- "state": The state parameter that was sent in the authorization request
If successful, the tokens are stored and the user is authenticated. If an error occurs, an HTTP error response is written to the response writer.
Parameters:
- w: The HTTP response writer
- r: The HTTP request containing the authorization callback
Example:
http.HandleFunc("/callback", flow.AuthorizationCodeReceivedHandler)
func (*AuthorizationCodeFlow) ExchangeCode ¶
func (flow *AuthorizationCodeFlow) ExchangeCode(ctx context.Context, authorizationCode string, receivedState string) error
Exchanges the authorization code for a token and established KindeContext
func (*AuthorizationCodeFlow) ExchangeDeviceAccessToken ¶ added in v0.0.3
func (flow *AuthorizationCodeFlow) ExchangeDeviceAccessToken(ctx context.Context, da *oauth2.DeviceAuthResponse, opts ...oauth2.AuthCodeOption) error
ExchangeDeviceAccessToken retrieves the access token for the device authorization flow.
func (*AuthorizationCodeFlow) GetAccountAPIClient ¶ added in v0.2.0
func (flow *AuthorizationCodeFlow) GetAccountAPIClient(ctx context.Context) (*account_api.Client, error)
GetAccountAPIClient returns an Account API client that uses the current user's access token. The client uses the token's issuer claim as the base URL.
func (*AuthorizationCodeFlow) GetAuthURL ¶
func (flow *AuthorizationCodeFlow) GetAuthURL() string
GetAuthURL returns the authorization URL to redirect users to for authentication.
This method generates the complete OAuth2 authorization URL with all configured parameters, including scopes, PKCE challenges (if enabled), custom auth parameters, and state. The URL should be used to redirect the user's browser to the authorization server.
The state parameter is automatically generated using the configured state generator (or a random value by default) to prevent CSRF attacks.
Returns the complete authorization URL as a string.
Example:
authURL := flow.GetAuthURL() http.Redirect(w, r, authURL, http.StatusFound)
func (*AuthorizationCodeFlow) GetAuthURLWithInvitation ¶ added in v0.2.0
func (flow *AuthorizationCodeFlow) GetAuthURLWithInvitation(invitationCode string) string
GetAuthURLWithInvitation returns the URL to redirect the user to start authentication pipeline with invitation code support. If invitationCode is provided, it will include both invitation_code and is_invitation parameters in the auth URL.
func (*AuthorizationCodeFlow) GetClient ¶
Returns the client to make requests to the backend, will refresh token if offline is requested.
func (*AuthorizationCodeFlow) InjectTokenMiddleware ¶ added in v0.1.3
func (flow *AuthorizationCodeFlow) InjectTokenMiddleware(next http.Handler) http.Handler
InjectTokenMiddleware injects the token into the request context for downstream handlers
func (*AuthorizationCodeFlow) IsAuthenticated ¶ added in v0.0.3
func (flow *AuthorizationCodeFlow) IsAuthenticated(ctx context.Context) (bool, error)
func (*AuthorizationCodeFlow) Logout ¶ added in v0.0.3
func (flow *AuthorizationCodeFlow) Logout() error
func (*AuthorizationCodeFlow) StartDeviceAuth ¶ added in v0.0.3
func (flow *AuthorizationCodeFlow) StartDeviceAuth(ctx context.Context) (*oauth2.DeviceAuthResponse, error)
StartDeviceAuth retrieves the device authorization response. It returns the device authorization response or an error if the request fails. This is used for the device authorization flow.
type IAuthorizationCodeFlow ¶ added in v0.0.4
type IAuthorizationCodeFlow interface {
// Returns the URL to redirect the user to start authentication pipeline.
GetAuthURL() string
// GetAuthURLWithInvitation returns the URL to redirect the user to start authentication pipeline
// with invitation code support. If invitationCode is provided, it will include both
// invitation_code and is_invitation parameters in the auth URL.
GetAuthURLWithInvitation(invitationCode string) string
// Exchanges the authorization code for a token and establishes KindeContext.
ExchangeCode(ctx context.Context, authorizationCode string, receivedState string) error
// Returns http client to call external services, will refresh token behind the scenes if offline is requested.
GetClient(ctx context.Context) (*http.Client, error)
// Check if user is authenticated.
IsAuthenticated(context.Context) (bool, error)
// Clears local tokens and logs user out.
Logout() error
// A helper handler middleware for the code exchanger
AuthorizationCodeReceivedHandler(w http.ResponseWriter, r *http.Request)
// InjectTokenMiddleware that injects the token into the request context
InjectTokenMiddleware(next http.Handler) http.Handler
// GetToken returns the validated JWT token.
GetToken(context.Context) (*jwt.Token, error)
}
IAuthorizationCodeFlow represents the interface for the authorization code flow.
func NewAuthorizationCodeFlow ¶
func NewAuthorizationCodeFlow(baseURL string, clientID string, clientSecret string, callbackURL string, options ...Option) (IAuthorizationCodeFlow, error)
NewAuthorizationCodeFlow creates a new AuthorizationCodeFlow for authenticating backend applications.
This function initializes an OAuth2 authorization code flow with the provided configuration. The flow handles the complete OAuth2 authorization code exchange process, including generating authorization URLs, handling callbacks, and exchanging codes for tokens.
Default scopes (openid, profile, email) are automatically prepended to any scopes specified in the options.
Parameters:
- baseURL: The base URL of your Kinde instance (e.g., "https://yourdomain.kinde.com")
- clientID: Your OAuth2 client ID
- clientSecret: Your OAuth2 client secret
- callbackURL: The redirect URI registered with your OAuth2 application
- options: Optional configuration functions to customize the flow behavior
Returns an IAuthorizationCodeFlow interface and an error if initialization fails.
Example:
flow, err := NewAuthorizationCodeFlow(
"https://yourdomain.kinde.com",
"your-client-id",
"your-client-secret",
"https://yourapp.com/callback",
WithScopes("openid", "profile", "email"),
WithPKCE(),
)
type IDeviceAuthorizationFlow ¶ added in v0.0.4
type IDeviceAuthorizationFlow interface {
// StartDeviceAuth starts the device authorization flow.
StartDeviceAuth(ctx context.Context) (*oauth2.DeviceAuthResponse, error)
// Exchanges the device code to access token.
ExchangeDeviceAccessToken(ctx context.Context, da *oauth2.DeviceAuthResponse, opts ...oauth2.AuthCodeOption) error
// Returns http client to call external services, will refresh token behind the scenes if offline is requested.
GetClient(ctx context.Context) (*http.Client, error)
// Checks if the user is authenticated.
IsAuthenticated(context.Context) (bool, error)
// Clears local tokens and logs user out.
Logout() error
// Returns the token for the current session.
GetToken(context.Context) (*jwt.Token, error)
}
IDeviceAuthorizationFlow represents the interface for the device authorization flow.
func NewDeviceAuthorizationFlow ¶ added in v0.0.3
func NewDeviceAuthorizationFlow(baseURL string, options ...Option) (IDeviceAuthorizationFlow, error)
NewDeviceAuthorizationFlow creates a new device authorization flow for OAuth2 device code grant.
The device authorization flow is designed for devices that lack a browser or have limited input capabilities. It allows users to authorize applications by entering a code on a separate device (e.g., a smartphone or computer).
Unlike the authorization code flow, this flow does not require a client secret or callback URL, making it suitable for public clients and constrained devices.
Parameters:
- baseURL: The base URL of your Kinde instance (e.g., "https://yourdomain.kinde.com")
- options: Optional configuration functions to customize the flow behavior
Returns an IDeviceAuthorizationFlow interface and an error if initialization fails.
Example:
flow, err := NewDeviceAuthorizationFlow(
"https://yourdomain.kinde.com",
WithScopes("openid", "profile", "email"),
)
type ISessionHooks ¶ added in v0.0.4
type ISessionHooks interface {
// SetRawToken stores the raw token in the session.
SetRawToken(token *oauth2.Token) error
// GetRawToken retrieves the raw token from the session.
GetRawToken() (*oauth2.Token, error)
// GetState retrieves the state from the session.
GetState() (string, error)
// SetState sets the state in the session.
SetState(state string) error
// SetPostAuthRedirect sets the post-authentication redirect URL in the session.
SetPostAuthRedirect(redirect string) error
// GetPostAuthRedirect retrieves the post-authentication redirect URL from the session.
GetPostAuthRedirect() (string, error)
// SetCodeVerifier stores the PKCE code verifier in the session.
SetCodeVerifier(codeVerifier string) error
// GetCodeVerifier retrieves the PKCE code verifier from the session.
GetCodeVerifier() (string, error)
}
ISessionHooks defines the interface for session management in the authorization code flow.
type Option ¶ added in v0.0.4
type Option func(*AuthorizationCodeFlow)
func WithAdditionalScope ¶ added in v0.0.3
WithAdditionalScope adds a scope to the existing list of authorization scopes.
Unlike WithScopes which replaces all scopes, this option appends a new scope to the current scope list. This is useful for incrementally adding scopes.
Parameters:
- scope: The scope string to add (e.g., "offline_access", "custom_scope")
Returns an Option that adds the scope to the authorization request.
Example:
flow, err := NewAuthorizationCodeFlow(baseURL, clientID, clientSecret, callbackURL,
WithScopes("openid", "profile"),
WithAdditionalScope("offline_access"),
)
func WithAudience ¶
WithAudience adds an audience parameter to the authorization request.
The audience parameter specifies which API or resource server the token is intended for. This is used in OAuth 2.0 flows where tokens are scoped to specific audiences.
Parameters:
- audience: The audience identifier (e.g., API endpoint URL or identifier)
Returns an Option that adds the audience parameter to the authorization URL.
Example:
flow, err := NewAuthorizationCodeFlow(baseURL, clientID, clientSecret, callbackURL,
WithAudience("https://api.example.com"),
)
func WithAuthParameter ¶
WithAuthParameter adds an arbitrary parameter to the authorization URL.
This option allows you to add custom query parameters to the authorization request URL. If the parameter already exists, the new value is appended to the existing values.
Parameters:
- name: The parameter name (e.g., "custom_param", "login_hint")
- value: The parameter value
Returns an Option that adds the specified parameter to the authorization URL.
Example:
flow, err := NewAuthorizationCodeFlow(baseURL, clientID, clientSecret, callbackURL,
WithAuthParameter("login_hint", "user@example.com"),
)
func WithClientID ¶ added in v0.0.3
WithClientID sets the OAuth2 client ID for the authorization flow.
The client ID identifies your application to the authorization server. This option allows you to override the client ID that was provided to NewAuthorizationCodeFlow.
Parameters:
- clientID: The OAuth2 client ID
Returns an Option that sets the client ID.
func WithClientSecret ¶ added in v0.0.3
WithClientSecret sets the OAuth2 client secret for the authorization flow.
The client secret is used to authenticate your application when exchanging authorization codes for tokens. This option allows you to override the client secret that was provided to NewAuthorizationCodeFlow.
Parameters:
- clientSecret: The OAuth2 client secret
Returns an Option that sets the client secret.
func WithCustomStateGenerator ¶
func WithCustomStateGenerator(stateFunc func(*AuthorizationCodeFlow) string) Option
WithCustomStateGenerator sets a custom function to generate the OAuth state parameter.
The state parameter is used to prevent CSRF attacks and to maintain state between the authorization request and callback. By default, a random state is generated.
This option allows you to provide a custom state generation function, which can be useful for maintaining application-specific state or integrating with session management systems.
Parameters:
- stateFunc: A function that receives the AuthorizationCodeFlow and returns a state string
Returns an Option that configures the custom state generator.
Example:
flow, err := NewAuthorizationCodeFlow(baseURL, clientID, clientSecret, callbackURL,
WithCustomStateGenerator(func(flow *AuthorizationCodeFlow) string {
return generateSecureState()
}),
)
func WithInvitationCode ¶ added in v0.2.0
WithInvitationCode sets the invitation code and is_invitation parameters for team member invitations. When an invitation code is provided, is_invitation will be set to "true".
func WithOffline ¶
func WithOffline() Option
WithOffline adds the "offline_access" scope to the authorization request.
The offline_access scope requests a refresh token that can be used to obtain new access tokens without requiring user interaction. This is useful for applications that need to access resources on behalf of the user when they are not actively using the app.
Returns an Option that adds the offline_access scope to the authorization request.
Example:
flow, err := NewAuthorizationCodeFlow(baseURL, clientID, clientSecret, callbackURL,
WithOffline(),
)
func WithPKCE ¶ added in v0.1.2
func WithPKCE() Option
Enables PKCE (Proof Key for Code Exchange) for enhanced security in public clients. This is recommended for applications that cannot securely store a client secret.
func WithPKCEChallengeMethod ¶ added in v0.1.2
WithPKCEChallengeMethod configures the PKCE challenge method for the authorization flow.
PKCE (Proof Key for Code Exchange) uses a code challenge to enhance security. This option allows you to specify which challenge method to use:
- "S256" (recommended): Uses SHA256 to hash the code verifier. This is the default and recommended method.
- "plain": Uses the code verifier directly without hashing. Less secure, only use if the authorization server doesn't support S256.
If an invalid method is provided, it defaults to "S256".
This option automatically enables PKCE and generates the code verifier and challenge based on the selected method. The code verifier is stored in session hooks if available.
Parameters:
- method: The challenge method to use ("S256" or "plain")
Returns an Option that configures PKCE with the specified challenge method.
Example:
flow, err := NewAuthorizationCodeFlow(baseURL, clientID, clientSecret, callbackURL,
WithPKCEChallengeMethod("S256"),
)
func WithPrompt ¶ added in v0.0.3
WithPrompt adds a prompt parameter to the authorization request.
The prompt parameter controls how the authorization server handles the authentication and consent UI. Common values include:
- "login": Forces the user to re-authenticate
- "consent": Forces the user to see the consent screen
- "select_account": Prompts the user to select an account
- "none": Prevents any UI from being shown (will fail if user is not authenticated)
Parameters:
- prompt: The prompt value to include in the authorization request
Returns an Option that adds the prompt parameter to the authorization URL.
Example:
flow, err := NewAuthorizationCodeFlow(baseURL, clientID, clientSecret, callbackURL,
WithPrompt("login"),
)
func WithReauthState ¶ added in v0.2.0
WithReauthState decodes a Base64-encoded JSON string containing re-authentication parameters and merges them into the authorization URL options.
The reauthState parameter is used to preserve authentication parameters during re-authentication flows. It should be a Base64-encoded JSON string containing login options that will be merged into the authorization request.
This is particularly useful when tokens expire and you need to re-authenticate the user while preserving their original authentication context (e.g., org_code, audience, scopes, etc.).
Parameters:
- reauthState: A Base64-encoded JSON string containing re-authentication parameters
Returns an Option that decodes and merges the reauth state parameters.
Example:
// reauthState is a Base64-encoded JSON like: {"org_code":"org123","audience":"api.example.com"}
flow, err := NewAuthorizationCodeFlow(baseURL, clientID, clientSecret, callbackURL,
WithReauthState(encodedReauthState),
)
func WithScopes ¶ added in v0.0.3
WithScopes sets the OAuth2 scopes for the authorization request.
Scopes define the permissions that your application is requesting from the user. This option replaces any existing scopes with the provided list. Default scopes (openid, profile, email) are automatically prepended if not explicitly included.
Parameters:
- scopes: One or more scope strings (e.g., "openid", "profile", "email", "offline_access")
Returns an Option that sets the authorization scopes.
Example:
flow, err := NewAuthorizationCodeFlow(baseURL, clientID, clientSecret, callbackURL,
WithScopes("openid", "profile", "email", "custom_scope"),
)
func WithSessionHooks ¶
func WithSessionHooks(sessionHooks ISessionHooks) Option
WithSessionHooks integrates the authorization flow with session management.
Session hooks allow you to customize how tokens and session data are stored and retrieved. This is essential for integrating with your application's session management system.
The ISessionHooks interface provides methods for:
- Storing and retrieving OAuth2 tokens
- Managing PKCE code verifiers
- Handling session state
Parameters:
- sessionHooks: An implementation of ISessionHooks for custom session management
Returns an Option that configures session management hooks.
Example:
flow, err := NewAuthorizationCodeFlow(baseURL, clientID, clientSecret, callbackURL,
WithSessionHooks(mySessionHooks),
)
func WithSupportsReauth ¶ added in v0.2.0
WithSupportsReauth adds the supports_reauth parameter to the authorization request.
The supports_reauth parameter indicates that the authentication instigator supports re-authentication on expired flows. This is used to enable re-authentication flows when tokens expire, allowing the application to prompt users to re-authenticate without losing their session context.
Returns an Option that adds the supports_reauth parameter to the authorization URL.
Example:
flow, err := NewAuthorizationCodeFlow(baseURL, clientID, clientSecret, callbackURL,
WithSupportsReauth(true),
)
func WithTokenValidation ¶
WithTokenValidation configures JWT token validation options.
This option allows you to enable JWKS-based token validation and provide additional JWT validation options. When isValidateJWKS is true, the flow will automatically validate tokens using the JWKS URL from the authorization server.
Parameters:
- isValidateJWKS: If true, enables automatic JWKS-based token validation
- tokenOptions: Additional JWT validation options (e.g., WillValidateIssuer, WillValidateAudience)
Returns an Option that configures token validation.
Example:
flow, err := NewAuthorizationCodeFlow(baseURL, clientID, clientSecret, callbackURL,
WithTokenValidation(true,
jwt.WillValidateIssuer("https://yourdomain.kinde.com"),
jwt.WillValidateAudience("your-client-id"),
),
)