### Build Go SDK Examples Source: https://github.com/descope/go-sdk/blob/main/README.md Build all example applications for the Descope Go SDK by running the 'make build' command. ```bash make build ``` -------------------------------- ### Example: Initiate NOTP SignIn Source: https://github.com/descope/go-sdk/blob/main/_autodocs/authentication-api.md Demonstrates how to call the NOTP SignIn function to start a WhatsApp authentication process. The response image should be displayed as a QR code for the user to scan. ```go resp, err := descopeClient.Auth.NOTP().SignIn( context.Background(), "", r, nil, ) // Show resp.Image as QR code // User scans and confirms in WhatsApp ``` -------------------------------- ### Run Specific Go SDK Example Source: https://github.com/descope/go-sdk/blob/main/README.md Execute a specific example application, such as the Gin web app or the Gorilla Mux web app, using the 'make run-' command. ```bash # Gin web app make run-gin-example ``` ```bash # Gorilla Mux web app make run-example ``` -------------------------------- ### Enchanted Link Get Session Example Usage Source: https://github.com/descope/go-sdk/blob/main/_autodocs/authentication-api.md Example demonstrating how to use SignIn to get a pending reference and then poll with GetSession to authenticate the user. ```go // Sign in returns PendingRef resp, _ := descopeClient.Auth.EnchantedLink().SignIn(ctx, email, uri, r, nil) pendingRef := resp.PendingRef // Poll until user clicks link ticker := time.NewTicker(1 * time.Second) for range ticker.C { authInfo, err := descopeClient.Auth.EnchantedLink().GetSession( ctx, pendingRef, w, ) if err == nil { // User authenticated! break } } ``` -------------------------------- ### Configuration Source: https://github.com/descope/go-sdk/blob/main/_autodocs/MANIFEST.txt Details on configuring the Descope Go SDK using environment variables, the Config struct, and various setup examples. ```APIDOC ## Configuration This section covers the various ways to configure the Descope Go SDK for different environments and requirements. ### Configuration Methods - **Environment Variables**: Supported environment variables include: - `DESCOPE_PROJECT_ID` - `DESCOPE_MANAGEMENT_KEY` - `DESCOPE_AUTH_MANAGEMENT_KEY` - `DESCOPE_PUBLIC_KEY` - `DESCOPE_BASE_URL` - **Config Struct**: A complete field reference for the `Config` struct, allowing programmatic configuration. ### Configuration Areas - **API Credentials**: Setting up project and management keys. - **Network Configuration**: Customizing timeouts, HTTP clients, and certificates. - **Custom Headers and Request IDs**: Adding custom headers and request IDs. - **Logging Configuration**: Configuring SDK logging behavior. - **Session Cookie Configuration**: Settings related to session cookies. - **Token Provider Customization**: Customizing token providers. - **JWT Leeway Settings**: Configuring JWT leeway. ### Examples Provides configuration examples for various scenarios: - Minimal configuration - Production and development setups - Multi-tenant configurations - Single Page Application (SPA) specific configurations - Setup examples for Docker, Docker Compose, and Kubernetes. ``` -------------------------------- ### Go SDK - SetTenantRoles Example Source: https://github.com/descope/go-sdk/blob/main/_autodocs/management-api.md Example of setting specific roles for a user within a given tenant. ```go updated, err := descopeClient.Management.User().SetTenantRoles( context.Background(), "user@example.com", "tenant-123", []string{"tenant-admin", "editor"}, ) ``` -------------------------------- ### Install Descope Go SDK Source: https://github.com/descope/go-sdk/blob/main/README.md Use this command to install the Descope SDK for Go. Ensure you are using Go version 1.18 or above. ```bash go get -u github.com/descope/go-sdk ``` -------------------------------- ### Start SSO (SAML) Flow (Deprecated) Source: https://github.com/descope/go-sdk/blob/main/README.md Deprecated method to initiate the SAML SSO authentication flow. Use `Auth.SSO().Start()` instead. It takes tenant ID and redirect URL, and returns a URL to start the SAML redirect chain. ```go //* Deprecated (use Auth.SSO().Start(..) instead) *// // // Choose which tenant to log into // If configured globally, the return URL is optional. If provided however, it will be used // instead of any global configuration. // Redirect the user to the returned URL to start the SSO/SAML redirect chain url, err := descopeClient.Auth.SAML().Start(context.Background(), "my-tenant-ID", "https://my-app.com/handle-saml", "", nil, nil, w) if err != nil { // handle error } ``` -------------------------------- ### Go SDK - SearchAll Example Source: https://github.com/descope/go-sdk/blob/main/_autodocs/management-api.md Demonstrates how to search for users with specific criteria like roles, tenant IDs, and statuses, and sort the results. ```go users, total, err := descopeClient.Management.User().SearchAll( context.Background(), &descope.UserSearchOptions{ Page: 0, Limit: 50, Text: "john", Roles: []string{"admin"}, TenantIDs: []string{"tenant-123"}, Statuses: []descope.UserStatus{descope.UserStatusEnabled}, Sort: []descope.UserSearchSort{ {Field: "createdTime", Desc: true}, }, }, ) log.Printf("Found %d users", total) ``` -------------------------------- ### Define Client Setup Error Source: https://github.com/descope/go-sdk/blob/main/_autodocs/errors.md This variable signifies a client setup error, specifically when the project ID is missing during client initialization. It prevents the SDK from functioning without essential configuration. ```go var ( ErrMissingProjectID = newClientError("G010001", "Missing project ID") ) ``` -------------------------------- ### Start WebAuthn Sign-Up Source: https://github.com/descope/go-sdk/blob/main/_autodocs/authentication-api.md Initiates the WebAuthn sign-up ceremony. Use this on the server-side to generate transaction details and options for the browser. ```go func (w WebAuthn) SignUpStart( ctx context.Context, loginID string, user *descope.User, origin string, signUpOptions *descope.SignUpOptions, ) (*descope.WebAuthnTransactionResponse, error) ``` ```go type WebAuthnTransactionResponse struct { TransactionID string // Send to finish step Options string // JSON for navigator.credentials.create() Create bool // true for registration } ``` ```go // Server generates transaction tx, err := descopeClient.Auth.WebAuthn().SignUpStart( context.Background(), "user@example.com", &descope.User{Name: "John Doe"}, "https://example.com", nil, ) if err != nil { return err } // Return tx.Options to browser ``` -------------------------------- ### Initiate OAuth SignUpOrIn Flow Source: https://github.com/descope/go-sdk/blob/main/_autodocs/authentication-api.md Use this function to start the OAuth sign-up or sign-in process with a specified provider. Ensure the return URL is correctly configured for the callback. ```go func (o OAuth) SignUpOrIn( ctx context.Context, provider descope.OAuthProvider, returnURL string, loginHint string, r *http.Request, loginOptions *descope.LoginOptions, w http.ResponseWriter, ) (string, error) ``` ```go // Initiate OAuth flow redirectURL, err := descopeClient.Auth.OAuth().SignUpOrIn( context.Background(), descope.OAuthGoogle, "https://app.example.com/auth/callback", "", r, nil, w, ) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } // w has been redirected to provider ``` -------------------------------- ### Start SSO (SAML/OIDC) Flow Source: https://github.com/descope/go-sdk/blob/main/README.md Initiates the SSO (SAML or OIDC) authentication flow for a specific tenant. The `redirectURL` parameter is used if provided, otherwise global configuration is used. The returned URL should be used to redirect the user to start the authentication chain. ```go // Choose which tenant to log into // If configured globally, the return URL is optional. If provided however, it will be used // instead of any global configuration. // Redirect the user to the returned URL to start the SSO SAML/OIDC redirect chain url, err := descopeClient.Auth.SSO().Start("my-tenant-ID", "https://my-app.com/handle-saml", "", "", "", nil, nil, w) if err != nil { // handle error } ``` -------------------------------- ### Initiate OAuth SignUp Flow Source: https://github.com/descope/go-sdk/blob/main/_autodocs/authentication-api.md Starts the OAuth sign-up process. Requires context, provider, return URL, and HTTP request/response objects. ```go func (o OAuth) SignUp( ctx context.Context, provider descope.OAuthProvider, returnURL string, loginHint string, r *http.Request, loginOptions *descope.LoginOptions, w http.ResponseWriter, ) (string, error) ``` -------------------------------- ### Initiate OAuth Sign-Up or Sign-In Source: https://github.com/descope/go-sdk/blob/main/README.md Starts an OAuth authentication flow for a specified provider. The return URL is optional if configured globally. The user is redirected to the returned URL to begin the OAuth process. ```go // Choose an oauth provider out of the supported providers // If configured globally, the return URL is optional. If provided however, it will be used // instead of any global configuration. // Redirect the user to the returned URL to start the OAuth redirect chain url, err := descopeClient.Auth.OAuth().SignUpOrIn(context.Background(), "google", "https://my-app.com/handle-oauth", "", nil, nil, w) if err != nil { // handle error } ``` -------------------------------- ### Get Tenant Settings Source: https://github.com/descope/go-sdk/blob/main/README.md Retrieves the current settings for a tenant. ```go // Load tenant settings by a tenant id settings, err := descopeClient.Management.Tenant().GetSettings(context.Background()) ``` -------------------------------- ### Initiate WebAuthn Sign-In Source: https://github.com/descope/go-sdk/blob/main/_autodocs/authentication-api.md Starts the WebAuthn sign-in ceremony on the server-side. This prepares the transaction for the browser to request the user's authenticator. ```go func (w WebAuthn) SignInStart( ctx context.Context, loginID string, origin string, r *http.Request, loginOptions *descope.LoginOptions, ) (*descope.WebAuthnTransactionResponse, error) ``` -------------------------------- ### Initiate OAuth SignIn Flow Source: https://github.com/descope/go-sdk/blob/main/_autodocs/authentication-api.md Starts the OAuth sign-in process. Requires context, provider, return URL, and HTTP request/response objects. ```go func (o OAuth) SignIn( ctx context.Context, provider descope.OAuthProvider, returnURL string, loginHint string, r *http.Request, loginOptions *descope.LoginOptions, w http.ResponseWriter, ) (string, error) ``` -------------------------------- ### Initiate nOTP WhatsApp Sign Up or In Source: https://github.com/descope/go-sdk/blob/main/README.md Initiates the nOTP (WhatsApp) sign-up or sign-in flow. The `loginID` can be an empty string or a phone number. The returned `RedirectURL` or `Image` is used to start the user's WhatsApp interaction, and `PendingRef` is used for polling. ```go loginID := "" // OR phone number res, err := descopeClient.Auth.NOTP().SignUpOrIn(context.Background(), loginID, nil, nil) if err != nil { // handle error } ``` -------------------------------- ### Get Tenant Settings Source: https://github.com/descope/go-sdk/blob/main/_autodocs/management-api.md Retrieves the session and token settings for a specific tenant. ```go func (t Tenant) GetSettings( ctx context.Context, tenantID string, ) (*descope.TenantSettings, error) ``` -------------------------------- ### SSO Start Source: https://github.com/descope/go-sdk/blob/main/_autodocs/authentication-api.md Initiates the SSO flow by redirecting the user to the Identity Provider (IdP). It requires tenant details, a return URL, and optionally accepts parameters for prompt behavior, specific SSO configuration, login hints, and additional login options. ```APIDOC ## SSO Start ### Description Initiates the SSO flow by redirecting the user to the Identity Provider (IdP). It requires tenant details, a return URL, and optionally accepts parameters for prompt behavior, specific SSO configuration, login hints, and additional login options. ### Method POST ### Endpoint /v1/auth/sso/start ### Parameters #### Path Parameters None #### Query Parameters * **tenant** (string) - Required - Tenant ID configured with SSO * **returnURL** (string) - Required - Redirect after authentication * **prompt** (string) - Optional - "none", "login", "consent", "select_account" (OIDC only) * **ssoID** (string) - Optional - Specific SSO config ID if multiple exist * **loginHint** (string) - Optional - Pre-fill hint for IdP #### Request Body * **loginOptions** (*descope.LoginOptions) - Optional - Options ### Request Example ```json { "tenant": "tenant-123", "returnURL": "https://app.example.com/auth/callback", "prompt": "", "ssoID": "", "loginHint": "", "loginOptions": null } ``` ### Response #### Success Response (200) * **redirectURL** (string) - IdP redirect URL #### Response Example ```json { "redirectURL": "https://idp.example.com/auth?samlRequest=..." } ``` ``` -------------------------------- ### SSO (SAML/OIDC) Start Flow Source: https://github.com/descope/go-sdk/blob/main/README.md Initiates an SSO (SAML or OIDC) authentication flow for a specified tenant. It returns a URL to redirect the user to, starting the authentication process with the identity provider. ```APIDOC ## Start SSO (SAML / OIDC) ### Description Initiates an SSO (SAML or OIDC) authentication flow for a specified tenant. This function returns a URL that the user should be redirected to, which starts the authentication redirect chain with the configured identity provider. An optional `http.ResponseWriter` can be provided to automatically set session cookies upon successful authentication. ### Method `descopeClient.Auth.SSO().Start(string, string, string, string, string, *string, *string, http.ResponseWriter)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go // Choose which tenant to log into // If configured globally, the return URL is optional. If provided however, it will be used // instead of any global configuration. // Redirect the user to the returned URL to start the SSO SAML/OIDC redirect chain url, err := descopeClient.Auth.SSO().Start("my-tenant-ID", "https://my-app.com/handle-saml", "", "", "", nil, nil, w) if err != nil { // handle error } ``` ### Response #### Success Response Returns a URL string that the user needs to be redirected to. #### Response Example ```json { "url": "https://sso.example.com/auth?request=..." } ``` ``` -------------------------------- ### Example Handler for Refreshing Session Source: https://github.com/descope/go-sdk/blob/main/_autodocs/session-validation.md This Go example demonstrates a handler function that uses `RefreshSessionRequest` to refresh session tokens. It handles potential errors and returns the new session and refresh JWTs. ```go func refreshHandler(w http.ResponseWriter, r *http.Request) { authInfo, err := descopeClient.Auth.RefreshSessionRequest( context.Background(), r, w, ) if err != nil { http.Error(w, "Failed to refresh", http.StatusUnauthorized) return } // Return new tokens to client w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(map[string]interface{}{ "sessionJwt": authInfo.SessionToken.JWT, "refreshJwt": authInfo.RefreshToken.JWT, }) } http.HandleFunc("/refresh", refreshHandler) ``` -------------------------------- ### Get User Tenants Source: https://github.com/descope/go-sdk/blob/main/README.md Retrieves the tenants associated with the current session user. The request requires a valid refresh token and can optionally include a boolean to get the current selected tenant or a list of tenant IDs. ```go // Refresh token will be taken from the request header or cookies automatically tenants, err := descopeClient.Auth.MyTenants(context.Background(), request, true, nil) if err == nil { for i := range tenants.Tenants { } } ``` -------------------------------- ### Sign Up User with Password Source: https://github.com/descope/go-sdk/blob/main/_autodocs/authentication-api.md Create a new user with a password. Ensure the password complies with the configured policy. Handles cases where the user already exists or the password fails validation. ```go func (p Password) SignUp( ctx context.Context, loginID string, user *descope.User, password string, w http.ResponseWriter, ) (*descope.AuthenticationInfo, error) ``` ```go authInfo, err := descopeClient.Auth.Password().SignUp( context.Background(), "user@example.com", &descope.User{Name: "John Doe"}, "SecurePassword123!", w, ) ``` -------------------------------- ### Get Tenant Settings Source: https://github.com/descope/go-sdk/blob/main/README.md Retrieves the settings for the current tenant. ```APIDOC ## Get Tenant Settings ### Description Retrieves the settings for the current tenant. ### Method GET ### Endpoint `/v1/tenant/settings` ### Parameters None ### Response #### Success Response (200) - **selfProvisioningDomains** (array of strings) - Domains for self-provisioning. - **refreshTokenExpiration** (integer) - The expiration time for refresh tokens. - **refreshTokenExpirationUnit** (string) - The unit for refresh token expiration (e.g., 'days'). - **sessionTokenExpiration** (integer) - The expiration time for session tokens. - **sessionTokenExpirationUnit** (string) - The unit for session token expiration (e.g., 'minutes'). - **enableInactivity** (boolean) - Whether to enable inactivity detection. - **inactivityTime** (integer) - The time period for inactivity. - **inactivityTimeUnit** (string) - The unit for inactivity time (e.g., 'days'). #### Response Example ```json { "selfProvisioningDomains": ["domain.com", "company.com"], "refreshTokenExpiration": 30, "refreshTokenExpirationUnit": "days", "sessionTokenExpiration": 30, "sessionTokenExpirationUnit": "minutes", "enableInactivity": true, "inactivityTime": 2, "inactivityTimeUnit": "days" } ``` ``` -------------------------------- ### Dockerfile for Descope Go Application Source: https://github.com/descope/go-sdk/blob/main/_autodocs/configuration.md This Dockerfile sets up a Go environment, copies the application code, downloads dependencies, builds the application, and configures Descope environment variables. ```dockerfile FROM golang:1.21-alpine WORKDIR /app COPY . . RUN go mod download RUN go build -o app . ENV DESCOPE_PROJECT_ID=my-project ENV DESCOPE_MANAGEMENT_KEY=secret_key_here ENV DESCOPE_BASE_URL=https://api.descope.com CMD ["./app"] ``` -------------------------------- ### Initialize Descope Client with Environment Variables Source: https://github.com/descope/go-sdk/blob/main/README.md Initializes the Descope client using environment variables for Project ID and Management Key. This is a convenient way to configure the client for management functions. ```go import "github.com/descope/go-sdk/descope/client" // Initialized after setting the DESCOPE_PROJECT_ID and the DESCOPE_MANAGEMENT_KEY env vars descopeClient, err := client.New() ``` -------------------------------- ### Get Descopers Source: https://github.com/descope/go-sdk/blob/main/README.md Retrieves a specific descoper using their unique ID. ```go // Get a specific descoper by ID descoper, err := descopeClient.Management.Descoper().Get(context.Background(), "descoper-id") ``` -------------------------------- ### Loading .env File and Initializing Descope Client Source: https://github.com/descope/go-sdk/blob/main/_autodocs/configuration.md This Go code snippet demonstrates how to load environment variables from a .env file using the godotenv package and then initialize the Descope client. ```go import "github.com/joho/godotenv" godotenv.Load() descopeClient, _ := client.New() ``` -------------------------------- ### Get Management Key Source: https://github.com/descope/go-sdk/blob/main/README.md Retrieves a specific management key using its unique ID. ```go // Get a management key by ID key, err := descopeClient.Management.ManagementKey().Get(context.Background(), "key-id") ``` -------------------------------- ### Get Password Settings Source: https://github.com/descope/go-sdk/blob/main/README.md Retrieves the current password settings for the project or a specific tenant. ```APIDOC ## Get Password Settings ### Description Retrieves the current password settings for the project or a specific tenant. ### Method `descopeClient.Management.Password().GetSettings(context.Context, string) (*PasswordSettings, error)` ### Parameters #### Path Parameters - **tenantID** (string) - Optional - The ID of the tenant. If omitted, project-level settings are retrieved. ### Response #### Success Response - **PasswordSettings** (*PasswordSettings) - An object containing the password settings. ``` -------------------------------- ### Basic Descope Client Initialization Source: https://github.com/descope/go-sdk/blob/main/_autodocs/client-initialization.md Initializes the Descope client with a project ID. This is the most basic configuration. ```go config := &client.Config{ ProjectID: "my-project-id", } descopeClient, err := client.NewWithConfig(config) ``` -------------------------------- ### Get Password Settings Source: https://github.com/descope/go-sdk/blob/main/README.md Retrieves password settings for either the project level or a specific tenant ID. ```go // You can get password settings for the project or for a specific tenant ID. settings, err := descopeClient.Management.Password().GetSettings(context.Background(), "tenant-id") ``` -------------------------------- ### Client Initialization Source: https://github.com/descope/go-sdk/blob/main/_autodocs/MANIFEST.txt Information on how to initialize the Descope client, including constructors and configuration options. ```APIDOC ## Client Initialization This section covers the entry points for initializing the Descope client in your Go application. ### Constructors - **New()**: Creates a new Descope client with default configuration. - **NewWithConfig(config Config)**: Creates a new Descope client with a custom configuration. ### Config Struct The `Config` struct provides a complete reference to all available configuration options, including API credentials, network settings, session cookie configuration, and more. ### Examples Provides various examples demonstrating different ways to configure and initialize the client for different environments and use cases. ``` -------------------------------- ### Session Validation Source: https://github.com/descope/go-sdk/blob/main/_autodocs/MANIFEST.txt Guides on validating user sessions, refreshing tokens, checking permissions, and integrating with HTTP middleware. ```APIDOC ## Session Validation This section covers how to validate user sessions, manage tokens, and check permissions within the Descope ecosystem. ### Core Functions - **ValidateSessionRequest()**: Validates an active user session. - **RefreshSessionRequest()**: Refreshes an expired session token. ### Permission and Tenant Operations - **IsPermitted(permission, resource)**: Checks if the current session has a specific permission. - **IsPermittedPerTenant(permission, resource, tenantID)**: Checks permissions within a specific tenant context. - **GetTenants()**: Retrieves the tenants associated with the current session. - **GetTenantValue(key)**: Retrieves a specific tenant value. ### Token Details - **AuthFactors**: Information about the authentication factors used in the session. - **IsMFA**: Indicates if Multi-Factor Authentication was used. - **CustomClaim(key)**: Accesses custom claims within the session token. ### Integration and Examples - **HTTP Middleware Integration**: Guidance on integrating session validation with HTTP middleware. - **Session Cookie Configuration**: Details on configuring session cookies. - **Token Extraction Methods**: Methods for extracting tokens from requests. - **Token Refresh Flow**: Examples of implementing token refresh. - **Complete Validation Examples**: End-to-end examples for session validation scenarios. ``` -------------------------------- ### Sign Up or In with Magic Link Source: https://github.com/descope/go-sdk/blob/main/_autodocs/authentication-api.md Initiates a flow that either signs up a new user or signs in an existing user using a magic link. This is a convenient method for handling both scenarios with a single call. Requires the user's login ID, a redirect URI, and optional sign-up options. ```go func (m MagicLink) SignUpOrIn( ctx context.Context, method descope.DeliveryMethod, loginID string, URI string, signUpOptions *descope.SignUpOptions, ) (maskedAddress string, err error) ``` -------------------------------- ### Sign Up User with Password Source: https://github.com/descope/go-sdk/blob/main/README.md Use this snippet to create a new user with a login ID and password. Ensure the login ID is unique and the password meets the configured requirements. The optional user object can contain additional profile information. ```go // Every user must have a loginID. All other user information is optional loginID := "desmond@descope.com" password := "qYlvi65KaX" user := &descope.User{ Name: "Desmond Copeland", GivenName: "Desmond", FamilyName: "Copeland", Email: loginID, } authInfo, err := descopeClient.Auth.Password().SignUp(context.Background(), loginID, user, password, nil) if err != nil { // handle error } ``` -------------------------------- ### Get User Authentication History - Go Source: https://github.com/descope/go-sdk/blob/main/_autodocs/management-api.md Retrieves the authentication history for one or more users. Requires a slice of user IDs. ```go func (u User) History( ctx context.Context, userIDs []string, ) ([]*descope.UserHistoryResponse, error) ``` ```go type UserHistoryResponse struct { UserID string // User ID LoginTime int32 // Unix timestamp City string // Geolocation city Country string // Geolocation country IP string // Source IP SelectedTenant string // Tenant used for login } ``` -------------------------------- ### Get Matched Permissions in Go Source: https://github.com/descope/go-sdk/blob/main/README.md Retrieves permissions that match the provided list for a user. This is used when not operating within a multi-tenant context. ```go matchedPermissions := descopeClient.Auth.GetMatchedPermissions(context.Background(), sessionToken, []string{"permission-name1", "permission-name2"}) ``` -------------------------------- ### Sign Up with OTP (Email) Source: https://github.com/descope/go-sdk/blob/main/README.md Initiates an OTP sign-up flow via email. Requires a login ID and optionally user details. Handles user already existing errors. ```go // Every user must have a loginID. // All other user information is optional loginID := "desmond@descope.com" user := &descope.User{ Name: "Desmond Copeland", GivenName: "Desmond", FamilyName: "Copeland", Phone: "212-555-1234", Email: loginID, } maskedAddress, err := descopeClient.Auth.OTP().SignUp(context.Background(), descope.MethodEmail, loginID, user, nil) if err != nil { if errors.Is(err, descope.ErrUserAlreadyExists) { // user already exists with this loginID } // handle other error cases } ``` -------------------------------- ### Get Matched Roles in Go Source: https://github.com/descope/go-sdk/blob/main/README.md Retrieves roles that match the provided list for a user. This is used when not operating within a multi-tenant context. ```go matchedRoles := descopeClient.Auth.GetMatchedRoles(context.Background(), sessionToken, []string{"role-name1", "role-name2"}) ``` -------------------------------- ### Create List Source: https://github.com/descope/go-sdk/blob/main/_autodocs/management-api.md Creates a new list (blocklist or allowlist). Requires context, name, description, list type, and data. ```go func (l Lists) Create( ctx context.Context, name string, description string, listType descope.ListType, data any, ) (*descope.List, error) ``` -------------------------------- ### Get User Tenants Source: https://github.com/descope/go-sdk/blob/main/_autodocs/session-validation.md Validates a session token and retrieves all tenants associated with the user. The tenant information is then encoded as JSON in the response. ```go func getUserTenantsHandler(w http.ResponseWriter, r *http.Request) { token, err := descopeClient.Auth.ValidateSessionRequest( context.Background(), r, ) if err != nil { http.Error(w, "Unauthorized", http.StatusUnauthorized) return } tenants := token.GetTenants() w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(map[string]interface{}{ "tenants": tenants, }) } ``` -------------------------------- ### Descope Client Initialization with Management Key Source: https://github.com/descope/go-sdk/blob/main/_autodocs/client-initialization.md Initializes the Descope client with a project ID and a management key. This enables access to management APIs. ```go config := &client.Config{ ProjectID: "my-project-id", ManagementKey: "mgmt-key-from-console", } descopeClient, err := client.NewWithConfig(config) // Now can use descopeClient.Management ``` -------------------------------- ### Enchanted Link Get Session Function Signature Source: https://github.com/descope/go-sdk/blob/main/_autodocs/authentication-api.md Signature for the GetSession function, used to poll for session status after enchanted link verification. ```go func (e EnchantedLink) GetSession( ctx context.Context, pendingRef string, w http.ResponseWriter, ) (*descope.AuthenticationInfo, error) ``` -------------------------------- ### Create Tenant Source: https://github.com/descope/go-sdk/blob/main/_autodocs/management-api.md Creates a new tenant with the specified configuration. Use this to onboard new organizations into your Descope project. ```go func (t Tenant) Create( ctx context.Context, tenantRequest *descope.TenantRequest, ) (id string, err error) ``` ```go tenantID, err := descopeClient.Management.Tenant().Create( context.Background(), &descope.TenantRequest{ Name: "ACME Corporation", SelfProvisioningDomains: []string{"acme.com", "acme-corp.com"}, EnforceSSO: true, }, ) ``` -------------------------------- ### Initialize Descope Client Source: https://github.com/descope/go-sdk/blob/main/_autodocs/INDEX.md Initialize the Descope client using environment variables or a configuration object. Ensure necessary environment variables are set or provide a client.Config struct. ```go import "github.com/descope/go-sdk/descope/client" descopeClient, err := client.New() // Uses env vars // or descopeClient, err := client.NewWithConfig(&client.Config{ ProjectID: "my-project", }) ``` -------------------------------- ### Get Authentication Factors Source: https://github.com/descope/go-sdk/blob/main/_autodocs/session-validation.md Retrieve the list of authentication methods used to authenticate the session. This is useful for auditing or conditional logic based on authentication strength. ```go token, _ := descopeClient.Auth.ValidateSessionRequest(ctx, r) factors := token.AuthFactors() for _, factor := range factors { log.Printf("User authenticated with: %s", factor) } ``` -------------------------------- ### WebAuthn SignUpStart Source: https://github.com/descope/go-sdk/blob/main/_autodocs/authentication-api.md Initiates the WebAuthn sign-up ceremony by generating transaction details and options for the browser's credential creation. ```APIDOC ## WebAuthn SignUpStart ### Description Initiate WebAuthn sign-up ceremony. ### Method Not applicable (SDK method) ### Endpoint Not applicable (SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go // Server generates transaction tx, err := descopeClient.Auth.WebAuthn().SignUpStart( context.Background(), "user@example.com", &descope.User{Name: "John Doe"}, "https://example.com", nil, ) if err != nil { return err } // Return tx.Options to browser ``` ### Response #### Success Response `*descope.WebAuthnTransactionResponse` containing `TransactionID` and `Options` for `navigator.credentials.create()`. #### Response Example ```json { "TransactionID": "some-transaction-id", "Options": "{\"publicKey\": { ... }}", "Create": true } ``` ``` -------------------------------- ### Minimal Descope Go SDK Configuration Source: https://github.com/descope/go-sdk/blob/main/_autodocs/configuration.md Use this minimal configuration when only a Project ID is available. It initializes the Descope client with essential settings. ```go config := &client.Config{ ProjectID: "my-project", } descopeClient, err := client.NewWithConfig(config) ``` -------------------------------- ### Get Custom Claim Value Source: https://github.com/descope/go-sdk/blob/main/_autodocs/session-validation.md Retrieve a custom claim value from a validated session token. Requires a valid session token and the claim key. ```go token, _ := descopeClient.Auth.ValidateSessionRequest(ctx, r) role := token.CustomClaim("role") department := token.CustomClaim("department") ``` -------------------------------- ### Create a User Source: https://github.com/descope/go-sdk/blob/main/_autodocs/management-api.md Use this function to create a new user in the project. It requires a login ID and can optionally include user details, roles, and tenant associations. Ensure the login ID is unique. ```go userResp, err := descopeClient.Management.User().Create( context.Background(), "john@example.com", &descope.UserRequest{ User: descope.User{ Name: "John Doe", Email: "john@example.com", Phone: "+1234567890", }, Roles: []string{"admin", "user"}, Tenants: []*descope.AssociatedTenant{ { TenantID: "tenant-123", TenantName: "ACME Corp", Roles: []string{"manager"}, }, }, }, ) ``` -------------------------------- ### WebAuthn Transaction Initialization Response Source: https://github.com/descope/go-sdk/blob/main/_autodocs/types.md Represents the initial response when starting a WebAuthn authentication ceremony. It includes a transaction ID and specific options for the client. ```go type WebAuthnTransactionResponse struct { TransactionID string // Transaction identifier Options string // WebAuthn options (JSON) Create bool // True for create, false for assertion } ``` -------------------------------- ### nOTP (WhatsApp) Get Session Source: https://github.com/descope/go-sdk/blob/main/README.md Polls for a valid nOTP (WhatsApp) session using a pending reference. This is called after the user sends the message via WhatsApp. ```APIDOC ## GetSession nOTP (WhatsApp) ### Description Polls for a valid nOTP (WhatsApp) session using the `PendingRef` obtained from the `SignUpOrIn` call. This function should be called repeatedly until a session is established or an error occurs. An optional `http.ResponseWriter` can be provided to automatically set session cookies. ### Method `descopeClient.Auth.NOTP().GetSession(context.Context, string, http.ResponseWriter)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go // Poll for a certain number of tries / time frame for i := retriesCount; i > 0; i-- { authInfo, err := descopeClient.Auth.NOTP().GetSession(context.Background(), res.PendingRef, w) if err == nil { // The user successfully authenticated break } if errors.Is(err, descope.ErrNOTPUnauthorized) && i > 1 { // poll again after X seconds time.Sleep(time.Second * time.Duration(retryInterval)) continue } if err != nil { // handle error break } } ``` ### Response #### Success Response (200) Returns authentication information including session and refresh JWTs upon successful user authentication. #### Response Example ```json { "sessionJwt": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", "refreshJwt": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." } ``` ``` -------------------------------- ### Project Structure Overview Source: https://github.com/descope/go-sdk/blob/main/_autodocs/overview.md Illustrates the directory structure of the Descope Go SDK, showing the organization of client, SDK interfaces, API communication, internal modules, and type definitions. ```go descope/ ├── client/ # Main SDK client initialization ├── sdk/ # Public interface definitions ├── api/ # HTTP client for API communication ├── internal/ │ ├── auth/ # Authentication implementations │ ├── mgmt/ # Management implementations │ └── utils/ # Internal utilities ├── types.go # Type definitions ├── errors.go # Error definitions ├── authztypes.go # Authorization type definitions └── logger/ # Logging interface ``` -------------------------------- ### Get Password Policy Requirements Source: https://github.com/descope/go-sdk/blob/main/_autodocs/authentication-api.md Retrieves the current password policy configuration, including minimum length and character type requirements. This can be used for client-side validation. ```go func (p Password) GetPasswordPolicy( ctx context.Context, ) (*descope.PasswordPolicy, error) ``` ```go policy, err := descopeClient.Auth.Password().GetPasswordPolicy( context.Background(), ) // Use to validate on client side before submission ``` -------------------------------- ### Set Temporary User Password Source: https://github.com/descope/go-sdk/blob/main/README.md Set a temporary password for a user that they will be required to change upon their next login. This is useful for initial setup or password resets. ```go // Set a temporary password for the user which they'll need to replace it on next login er := descopeClient.Management.User().SetTemporaryPassword(context.Background(), "", "") ``` -------------------------------- ### Create User Source: https://github.com/descope/go-sdk/blob/main/README.md Creates a new user with the specified login ID and user request details. ```go user, err := descopeClient.Management.User().Create(context.Background(), "desmond@descope.com", userReq) ``` -------------------------------- ### OTP SignUpOrIn with Email Source: https://github.com/descope/go-sdk/blob/main/_autodocs/authentication-api.md Sign up or sign in a user with OTP via email. This method can be used for both new and existing users and accepts optional sign-up configurations. ```go masked, err := descopeClient.Auth.OTP().SignUpOrIn( context.Background(), descope.MethodEmail, "user@example.com", nil, ) ``` -------------------------------- ### Check for Management User Not Found Error Source: https://github.com/descope/go-sdk/blob/main/_autodocs/errors.md This example shows how to check if a management operation failed because the user was not found, using the descope.IsError() function with the specific error code. ```go user, err := descopeClient.Management.User().Load(ctx, "user@example.com") if descope.IsError(err, "E112102") { log.Println("User not found") } ``` -------------------------------- ### Check for Validation Failure Error Source: https://github.com/descope/go-sdk/blob/main/_autodocs/errors.md Example of how to check if an error is specifically a validation failure using errors.Is(). This is useful for providing user feedback on invalid input data. ```go if errors.Is(err, descope.ErrValidationFailure) { log.Println("Invalid input data") } ``` -------------------------------- ### Get Tenant-Specific Claim Value Source: https://github.com/descope/go-sdk/blob/main/_autodocs/session-validation.md Retrieve a tenant-specific claim value from a validated session token. Requires a valid session token and the tenant ID and claim key. ```go token, _ := descopeClient.Auth.ValidateSessionRequest(ctx, r) orgName := token.GetTenantValue("tenant-123", "org_name") ``` -------------------------------- ### Initialize Descope Client with Configuration Object Source: https://github.com/descope/go-sdk/blob/main/README.md Initializes the Descope client directly with a configuration object, specifying Project ID, Management Key, and Auth Management Key. This provides explicit control over client configuration. ```go import "github.com/descope/go-sdk/descope/client" // ** Or directly ** descopeClient, err := client.NewWithConfig(&client.Config{ ProjectID: "project-ID", // ManagementKey is required to use any of the management functions // It is not used to access authentication methods with disabled public access ManagementKey: "management-key", // AuthManagementKey is required to access authentication methods with disabled public access // It is not used to access any of the management functions AuthManagementKey: "auth-management-key", }) ``` -------------------------------- ### Define Sign-Up Options Structure Source: https://github.com/descope/go-sdk/blob/main/_autodocs/types.md Defines the structure for sign-up options, allowing customization of token claims, email templates, and associated tenant. ```go type SignUpOptions struct { CustomClaims map[string]any // Custom claims in token TemplateID string // Email template override TemplateOptions map[string]string // Template variables TenantID string // Associated tenant } ``` -------------------------------- ### Start SSO Flow Source: https://github.com/descope/go-sdk/blob/main/_autodocs/authentication-api.md Initiates the SSO authentication flow by redirecting the user to the Identity Provider (IdP). Use this method to begin the SAML or OIDC login process. ```go func (s SSOServiceProvider) Start( ctx context.Context, tenant string, returnURL string, prompt string, ssoID string, loginHint string, r *http.Request, loginOptions *descope.LoginOptions, w http.ResponseWriter, ) (redirectURL string, err error) ``` ```go redirectURL, err := descopeClient.Auth.SSO().Start( context.Background(), "tenant-123", "https://app.example.com/auth/callback", "", "", "", r, nil, w, ) // User redirected to IdP ``` -------------------------------- ### Tenant.Create Source: https://github.com/descope/go-sdk/blob/main/_autodocs/management-api.md Creates a new tenant with the specified configuration. Returns the unique identifier of the newly created tenant. ```APIDOC ## Tenant.Create ### Description Create a new tenant. ### Method ```go func (t Tenant) Create( ctx context.Context, tenantRequest *descope.TenantRequest, ) (id string, err error) ``` ### Parameters #### Path Parameters - **ctx** (context.Context) - Required - Request context - **tenantRequest** (*descope.TenantRequest) - Required - Tenant configuration ### Response #### Success Response - **id** (string) - Tenant ID - **err** (error) - Error object if creation fails ### Request Example ```go tenantID, err := descopeClient.Management.Tenant().Create( context.Background(), &descope.TenantRequest{ Name: "ACME Corporation", SelfProvisioningDomains: []string{"acme.com", "acme-corp.com"}, EnforceSSO: true, }, ) ``` ``` -------------------------------- ### SignUp Source: https://github.com/descope/go-sdk/blob/main/_autodocs/authentication-api.md Creates a new user with a specified login ID and password. User details can optionally be provided. ```APIDOC ## SignUp Create user with password. ### Function Signature ```go func (p Password) SignUp( ctx context.Context, loginID string, user *descope.User, password string, w http.ResponseWriter, ) (*descope.AuthenticationInfo, error) ``` ### Parameters #### Path Parameters * None #### Query Parameters * None #### Request Body * None (parameters are passed directly) ### Parameters Details - **ctx** (context.Context) - Required - Request context - **loginID** (string) - Required - Email or username - **user** (*descope.User) - Optional - User details - **password** (string) - Required - Must comply with password policy - **w** (http.ResponseWriter) - Optional - ResponseWriter ### Throws/Rejects - `descope.ErrUserAlreadyExists` - User exists - `descope.ErrValidationFailure` - Password doesn't meet policy ### Example ```go authInfo, err := descopeClient.Auth.Password().SignUp( context.Background(), "user@example.com", &descope.User{Name: "John Doe"}, "SecurePassword123!", w, ) ``` ``` -------------------------------- ### Example: Poll for WhatsApp Session Confirmation Source: https://github.com/descope/go-sdk/blob/main/_autodocs/authentication-api.md Illustrates how to use a ticker to periodically call GetSession with a pending reference obtained from a previous SignIn or SignUp operation, until the user is authenticated. ```go // After SignIn/SignUp returns PendingRef ticker := time.NewTicker(1 * time.Second) for range ticker.C { authInfo, err := descopeClient.Auth.NOTP().GetSession( ctx, resp.PendingRef, w, ) if err == nil { // User authenticated break } } ``` -------------------------------- ### Handle User Already Exists Error Source: https://github.com/descope/go-sdk/blob/main/_autodocs/errors.md This example demonstrates checking if a user already exists during a sign-up attempt. If ErrUserAlreadyExists is returned, it suggests using a sign-in flow instead. ```go _, err := descopeClient.Auth.OTP().SignUp(ctx, method, loginID, user, nil) if errors.Is(err, descope.ErrUserAlreadyExists) { log.Println("User already registered, use SignIn instead") } ``` -------------------------------- ### Create Tenant Source: https://github.com/descope/go-sdk/blob/main/README.md Creates a new tenant with the specified name and request details. Optionally, a custom ID can be provided. ```go // Create tenant err := descopeClient.Management.Tenant().Create(context.Background(), "My Tenant", tenantRequest) ``` ```go // You can optionally set your own ID when creating a tenant err := descopeClient.Management.Tenant().CreateWithID(context.Background(), "my-custom-id", tenantRequest) ``` -------------------------------- ### Get Matched Tenant Permissions in Go Source: https://github.com/descope/go-sdk/blob/main/README.md Retrieves permissions that match the provided list for a user within a specific tenant. Requires a valid session token and tenant ID. ```go matchedTenantPermissions := descopeClient.Auth.GetTenantPermissions(context.Background(), sessionToken, "my-tenant-ID", []string{"permission-name1", "permission-name2"}) ``` -------------------------------- ### Import Logging Source: https://github.com/descope/go-sdk/blob/main/_autodocs/INDEX.md Import the logging package for Descope SDK. ```go import "github.com/descope/go-sdk/descope/logger" ``` -------------------------------- ### Get Matched Tenant Roles in Go Source: https://github.com/descope/go-sdk/blob/main/README.md Retrieves roles that match the provided list for a user within a specific tenant. Requires a valid session token and tenant ID. ```go matchedTenantRoles := descopeClient.Auth.GetTenantRoles(context.Background(), sessionToken, "my-tenant-ID", []string{"role-name1", "role-name2"}) ``` -------------------------------- ### Create Permission Source: https://github.com/descope/go-sdk/blob/main/_autodocs/management-api.md Use this function to create a new permission. It requires a context, permission name, and description. ```go func (p Permission) Create( ctx context.Context, name string, description string, ) (*descope.Permission, error) ``` -------------------------------- ### Get User Authentication History Source: https://github.com/descope/go-sdk/blob/main/README.md Retrieve the authentication history for one or more users, identified by their user IDs. The history includes details like login time, location, and IP address. ```go // Get users' authentication history loginHistoryRes, err := descopeClient.Management.User().History(context.Background(), []string{"", ""}) if err == nil { for i := range loginHistoryRes { fmt.Println(loginHistoryRes[i].UserID) fmt.Println(loginHistoryRes[i].City) fmt.Println(loginHistoryRes[i].Country) fmt.Println(loginHistoryRes[i].IP) fmt.Println(loginHistoryRes[i].LoginTime) } } ``` -------------------------------- ### Initialize Descope Client with Explicit Configuration Source: https://github.com/descope/go-sdk/blob/main/_autodocs/client-initialization.md Create a new Descope client by providing an explicit configuration struct. This allows for detailed control over settings like API keys, base URL, and JWT options. ```go package main import ( "time" "github.com/descope/go-sdk/descope/client" ) func main() { config := &client.Config{ ProjectID: "my-project-id", ManagementKey: "mgmt-key-from-console", AuthManagementKey: "auth-mgmt-key", DescopeBaseURL: "https://api.descope.com", JWTLeeway: 30 * time.Second, SessionJWTViaCookie: true, SessionJWTCookieDomain: "example.com", } descopeClient, err := client.NewWithConfig(config) if err != nil { panic(err) } // Use descopeClient } ``` -------------------------------- ### Handle Rate Limit Exceeded Error Source: https://github.com/descope/go-sdk/blob/main/_autodocs/errors.md This example demonstrates how to check for a rate limit exceeded error and extract the 'Retry-After' value from the error's Info map to determine when to resend the request. ```go if descope.IsError(err, "E130429") { retryAfter := err.Info[descope.ErrorInfoKeys.RateLimitExceededRetryAfter] log.Printf("Rate limited, retry after %v seconds", retryAfter) } ``` -------------------------------- ### Create Outbound Application Source: https://github.com/descope/go-sdk/blob/main/README.md Creates a new outbound application. Populate the required fields like Name and Description. ```go // Create an outbound application app, err := descopeClient.Management.OutboundApplication().CreateApplication(context.Background(), &descope.OutboundApp{ Name: "My Outbound App", Description: "Description", // ... other fields ... }) ``` -------------------------------- ### Load All Lists Source: https://github.com/descope/go-sdk/blob/main/_autodocs/management-api.md Retrieves all lists associated with the project. Requires context. ```go func (l Lists) LoadAll( ctx context.Context, ) ([]*descope.List, error) ```