authorization_code

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: May 25, 2026 License: MIT Imports: 14 Imported by: 1

README

Authorization Code Flow

The authorization_code package provides OAuth2 authorization code flow implementations for Go applications. This package is imported as github.com/kinde-oss/kinde-go/oauth2/authorization_code.

Overview

The authorization code flow is a backend authorization flow that requires a client secret. It is designed to be used as a server-side auth flow and does not expose tokens to the browser. User sessions need to be managed by other means, for example via session cookies.

Go Imports

import (
    "github.com/kinde-oss/kinde-go/oauth2/authorization_code" // required
    "github.com/kinde-oss/kinde-go/jwt" // optional - for JWT token validation
)

Standard Authorization Code Flow

Basic Usage
kindeAuthFlow, err := authorization_code.NewAuthorizationCodeFlow(
  "<issuer URL>",                                       // Kinde subdomain or any auth provider conforming to the spec
  "<client_id>", "<client_secret>", "<callback URL>",
  authorization_code.WithSessionHooks(<ISessionHooks implementation>),     // example of storage for gin framework is gin_kinde.UseKindeAuth(...)
  authorization_code.WithOffline(),                                        // adds offline scope and starts managing refresh tokens
  authorization_code.WithAudience("<your API audience>"),                  // requesting an API audience
  authorization_code.WithTokenValidation(
    true,                                               // will validate token signature via JWKS
    jwt.WillValidateAlgorithm(),                        // will validate the token alg is RS256
    jwt.WillValidateAudience("<your API audience>"),    // will confirm that received token includes correct audience
  ),
)
Available Methods
Method Description Parameters Returns
GetAuthURL Returns the URL to redirect the user to start the authentication pipeline. none string
ExchangeCode Exchanges the authorization code for a token and establishes KindeContext. ctx context.Context, authorizationCode string, receivedState string error
GetClient Returns an HTTP client for calling external services, automatically refreshing tokens if offline is requested. ctx context.Context (*http.Client, error)
IsAuthenticated Checks if the user is authenticated. ctx context.Context (bool, error)
Logout Clears local tokens and logs the user out. none error
AuthorizationCodeReceivedHandler Helper handler middleware for the code exchanger. w http.ResponseWriter, r *http.Request none

Device Authorization Flow

The device authorization flow is an extension of the authorization code flow that separates token requester and receiver. It is best used for devices and environments with limited input capabilities, such as CLIs, TVs, etc.

Basic Usage
deviceFlow, err := authorization_code.NewDeviceAuthorizationFlow(
  "<issuer_domain>",                                    // Kinde subdomain or any auth provider conforming to the spec
  authorization_code.WithClientID("<your-client-id>"),  // optional, when business provides a default device application, otherwise required
  authorization_code.WithClientSecret("<your-client-secret>"), // optional (used when device flow is used against backend application with a secret)
  authorization_code.WithSessionHooks(<ISessionHooks implementation>),      // used for storing/retrieving tokens
  authorization_code.WithOffline(),                     // optional - include if you'd like to maintain refresh tokens and a long session
  authorization_code.WithTokenValidation(
    true,                                               // will validate token signature via JWKS
    jwt.WillValidateAlgorithm(),                        // will validate the token alg is RS256
  ),
)
Available Methods
Method Description Parameters Returns
StartDeviceAuth Starts the device authorization flow and returns the device authorization response. ctx context.Context (*oauth2.DeviceAuthResponse, error)
ExchangeDeviceAccessToken Exchanges the device code for an access token. ctx context.Context, da *oauth2.DeviceAuthResponse, opts ...oauth2.AuthCodeOption error
GetClient Returns an HTTP client for calling external services, automatically refreshing tokens if offline is requested. ctx context.Context (*http.Client, error)
IsAuthenticated Checks if the user is authenticated. ctx context.Context (bool, error)
Logout Clears local tokens and logs the user out. none error
GetToken Returns the token for the current session. ctx context.Context (*jwt.Token, error)
InjectTokenMiddleware Middleware that injects the auth token into request context. next http.Handler http.Handler

Middleware

The authorization code flow package provides several middleware options to simplify integration with popular Go web frameworks and HTTP handlers.

Built-in HTTP Handler Middleware

The AuthorizationCodeReceivedHandler method provides a built-in HTTP handler for processing OAuth2 callbacks:

// Set up your callback route
http.HandleFunc("/callback", func(w http.ResponseWriter, r *http.Request) {
    kindeAuthFlow.AuthorizationCodeReceivedHandler(w, r)
})

This handler automatically:

  • Extracts the authorization code and state from the request
  • Validates the state parameter
  • Exchanges the code for tokens
  • Stores the tokens using your session hooks
Gin Framework Middleware

For Gin applications, use the gin_kinde package which provides a complete middleware solution:

import "github.com/kinde-oss/kinde-go/frameworks/gin_kinde"

func main() {
    router := gin.Default()

    // Set up session middleware
    store := sessions.NewStore(...)
    router.Use(sessions.Sessions("kinde-session", store))

    // Create a protected route group
    privateGroup := router.Group("/")

    // Apply Kinde authentication middleware
    gin_kinde.UseKindeAuth(privateGroup,
        "https://your-tenant.kinde.com",    // Kinde domain
        "your-client-id",                  // Client ID
        "your-client-secret",              // Client secret
        "http://localhost:8080",           // Base redirect URL
        authorization_code.WithPrompt("login"),
        authorization_code.WithOffline(),
    )

    // All routes in privateGroup are now protected
    privateGroup.GET("/profile", func(c *gin.Context) {
        // User is authenticated here
        c.JSON(200, gin.H{"message": "Authenticated!"})
    })

    router.Run(":8080")
}

The gin_kinde.UseKindeAuth middleware:

  1. Initializes the auth flow for each request
  2. Handles the callback at /kinde/callback automatically
  3. Protects all routes in the group by checking authentication
  4. Redirects unauthenticated users to the authorization URL
  5. Provides the Kinde client in the Gin context for additional operations
Custom Middleware Implementation

You can create custom middleware for other frameworks or specific use cases:

func AuthMiddleware(kindeFlow *authorization_code.AuthorizationCodeFlow) func(http.Handler) http.Handler {
    return func(next http.Handler) http.Handler {
        return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            // Check if user is authenticated
            isAuthenticated, err := kindeFlow.IsAuthenticated(r.Context())
            if err != nil || !isAuthenticated {
                // Redirect to authorization URL
                http.Redirect(w, r, kindeFlow.GetAuthURL(), http.StatusFound)
                return
            }

            // User is authenticated, continue to next handler
            next.ServeHTTP(w, r)
        })
    }
}

// Usage with standard http package
func main() {
    kindeFlow, _ := authorization_code.NewAuthorizationCodeFlow(...)

    mux := http.NewServeMux()
    mux.HandleFunc("/protected", protectedHandler)

    // Apply middleware
    handler := AuthMiddleware(kindeFlow)(mux)

    http.ListenAndServe(":8080", handler)
}
Middleware Features

All middleware implementations provide:

  • Automatic authentication checking on protected routes
  • Seamless redirects to the authorization server
  • Session management integration
  • Token validation and refresh handling
  • Error handling with appropriate HTTP status codes
Middleware Configuration Options

When setting up middleware, you can pass the same options used in the authorization flow:

gin_kinde.UseKindeAuth(privateGroup,
    kindeDomain,
    clientID,
    clientSecret,
    baseRedirectURL,
    authorization_code.WithOffline(),                    // Enable refresh tokens
    authorization_code.WithAudience("your-api"),        // Request specific audience
    authorization_code.WithPKCE(),                      // Enable PKCE for public clients
    authorization_code.WithTokenValidation(true),       // Enable token validation
)

These options are automatically applied to the authorization flow created by the middleware.

Session Management

Both flows require session hooks to be implemented for token storage and retrieval. The session hooks interface allows you to customize how tokens are stored and retrieved based on your application's needs.

Token Validation

Both flows support comprehensive token validation options:

  • Signature Validation: Validates token signatures using JWKS
  • Algorithm Validation: Ensures tokens use the expected algorithm (e.g., RS256)
  • Audience Validation: Confirms tokens include the correct API audience
  • Custom Validation: Additional validation rules can be implemented

Offline Support

When using WithOffline(), the flows will:

  • Request offline scope from the authorization server
  • Manage refresh tokens automatically
  • Maintain long-term sessions
  • Automatically refresh expired access tokens

Examples

For complete examples demonstrating these flows, see the examples/ directory in the main repository:

  • Gin Chat Example: Shows how to integrate authorization code flow with a Gin web application
  • CLI Example: Demonstrates device authorization flow with secure token storage

Security Considerations

  • Always use HTTPS in production
  • Implement proper session management
  • Store tokens securely using the provided session hooks
  • Validate tokens on each request
  • Implement proper logout procedures
  • Use appropriate scopes and audiences for your application

Dependencies

This package requires Go 1.24+ and depends on the following packages:

  • github.com/kinde-oss/kinde-go/jwt - For JWT token handling and validation
  • Standard Go packages: context, net/http, oauth2

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ExampleCustomMiddleware added in v0.1.3

func ExampleCustomMiddleware(next http.Handler) http.Handler

ExampleCustomMiddleware demonstrates how to create custom middleware that uses the Kinde token.

This example shows how to build custom middleware that:

  1. Extracts the token from the request context (set by Kinde middleware)
  2. Performs custom authorization checks (e.g., scope validation)
  3. Handles unauthorized/forbidden cases
  4. 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:

  1. Create an authorization flow
  2. Extract tokens from request context in handlers
  3. 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

func TokenFromContext(ctx context.Context) (*jwt.Token, bool)

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

func (flow *AuthorizationCodeFlow) GetClient(ctx context.Context) (*http.Client, error)

Returns the client to make requests to the backend, will refresh token if offline is requested.

func (*AuthorizationCodeFlow) GetToken added in v0.0.3

func (flow *AuthorizationCodeFlow) GetToken(ctx context.Context) (*jwt.Token, error)

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

func WithAdditionalScope(scope string) Option

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

func WithAudience(audience string) Option

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

func WithAuthParameter(name, value string) Option

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

func WithClientID(clientID string) Option

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

func WithClientSecret(clientSecret string) Option

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

func WithInvitationCode(invitationCode string) Option

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

func WithPKCEChallengeMethod(method string) Option

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

func WithPrompt(prompt string) Option

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

func WithReauthState(reauthState string) Option

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

func WithScopes(scopes ...string) Option

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

func WithSupportsReauth(supportsReauth bool) Option

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

func WithTokenValidation(isValidateJWKS bool, tokenOptions ...func(*jwt.Token)) Option

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"),
    ),
)

Jump to

Keyboard shortcuts

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