### Install gocloak Source: https://github.com/nerzal/gocloak/blob/main/README.md Use `go get` to install the latest version of the gocloak package. ```shell go get github.com/Nerzal/gocloak/v14 ``` -------------------------------- ### Managing Clients: Create, Get Secret, Get Service Account Source: https://github.com/nerzal/gocloak/blob/main/_autodocs/README.md Provides examples for managing clients in Keycloak, including creating a new client, retrieving a client's secret, and fetching a client's service account details. ```go // Create client client := gocloak.Client{ ClientID: gocloak.StringP("my-app"), Enabled: gocloak.BoolP(true), StandardFlowEnabled: gocloak.BoolP(true), RedirectURIs: []string{"https://app.example.com/callback"}, } clientID, err := client.CreateClient(ctx, token, "realm", client) ``` ```go // Get client secret secret, err := client.GetClientSecret(ctx, token, "realm", clientID) ``` ```go // Get service account serviceAccount, err := client.GetClientServiceAccount(ctx, token, "realm", clientID) ``` -------------------------------- ### Get Keystore Configuration - GoCloak Source: https://github.com/nerzal/gocloak/blob/main/_autodocs/api-reference/server-info-and-identity-providers.md Gets the keystore configuration for a realm, including active keys and the key list. Requires an admin access token. ```go func (g *GoCloak) GetKeyStoreConfig(ctx context.Context, token, realm string) (*KeyStoreConfig, error) ``` -------------------------------- ### Create Resource Go Example Source: https://github.com/nerzal/gocloak/blob/main/_autodocs/api-reference/authorization-and-events.md Use this to create a new resource associated with a client. Requires an admin access token and the client's internal ID. ```go resource := gocloak.ResourceRepresentation{ Name: gocloak.StringP("document"), DisplayName: gocloak.StringP("Document Resource"), Type: gocloak.StringP("urn:document:model"), URIs: []string{"/documents", "/documents/*"}, } created, err := client.CreateResource(ctx, token, "myrealm", "client-id", resource) ``` -------------------------------- ### CreateClient Go Example Source: https://github.com/nerzal/gocloak/blob/main/_autodocs/api-reference/clients-management.md Use this to create a new OAuth2/OpenID Connect client in a realm. It returns only the client ID. Ensure you have an admin access token and the realm name. ```go newClient := gocloak.Client{ ClientID: gocloak.StringP("my-app"), Name: gocloak.StringP("My Application"), Enabled: gocloak.BoolP(true), PublicClient: gocloak.BoolP(false), StandardFlowEnabled: gocloak.BoolP(true), RedirectURIs: []string{"https://app.example.com/callback"}, } clientID, err := client.CreateClient(ctx, token, "myrealm", newClient) ``` -------------------------------- ### Get Clients Optional Scopes Source: https://github.com/nerzal/gocloak/blob/main/_autodocs/api-reference/clients-management.md Gets the list of optional client scopes for a client. Requires an admin access token and the client's internal ID. ```go func (g *GoCloak) GetClientsOptionalScopes(ctx context.Context, token, realm, idOfClient string) ([]*ClientScope, error) ``` -------------------------------- ### Create User with Pointer Fields Source: https://github.com/nerzal/gocloak/blob/main/_autodocs/README.md Example of constructing a User type using pointer helper functions for optional fields like Username, Email, and Enabled. ```go // In type constructors user := gocloak.User{ Username: gocloak.StringP("john.doe"), Email: gocloak.StringP("john@example.com"), Enabled: gocloak.BoolP(true), } ``` -------------------------------- ### OAuth2 Client Setup with GoCloak Source: https://github.com/nerzal/gocloak/blob/main/_autodocs/README.md Shows how to create an OAuth2 client, define its properties like redirect URIs, create a client role, and assign that role to a user. ```go // Create client client := gocloak.Client{ ClientID: gocloak.StringP("mobile-app"), Name: gocloak.StringP("Mobile App"), PublicClient: gocloak.BoolP(true), StandardFlowEnabled: gocloak.BoolP(true), RedirectURIs: []string{"app://callback"}, } clientID, _ := client.CreateClient(ctx, token, "realm", client) // Add client role role := gocloak.Role{Name: gocloak.StringP("user")} client.CreateClientRole(ctx, token, "realm", clientID, role) // Assign role to user roles := []gocloak.Role{{Name: gocloak.StringP("user")}} client.AddClientRolesToUser(ctx, token, "realm", clientID, userID, roles) ``` -------------------------------- ### Get Client Roles By User ID Go Source: https://github.com/nerzal/gocloak/blob/main/_autodocs/api-reference/users-management.md Gets all client-level roles assigned to a user for a specific client. Requires context, admin token, realm name, client ID, and user ID. ```go func (g *GoCloak) GetClientRolesByUserID(ctx context.Context, token, realm, idOfClient, userID string) ([]*Role, error) ``` -------------------------------- ### Basic Usage: Authenticate and Get User Source: https://github.com/nerzal/gocloak/blob/main/_autodocs/README.md Demonstrates creating a client, authenticating as an admin, and retrieving a user by ID. Ensure you replace placeholder values with your Keycloak instance details. ```go package main import ( "context" "fmt" "github.com/Nerzal/gocloak/v14" ) func main() { // Create client client := gocloak.NewClient("https://keycloak.example.com") ctx := context.Background() // Authenticate token, err := client.LoginAdmin(ctx, "admin", "password", "master") if err != nil { panic(err) } // Get user user, err := client.GetUserByID(ctx, token.AccessToken, "myrealm", "user-123") if err != nil { panic(err) } fmt.Printf("User: %s\n", *user.Username) } ``` -------------------------------- ### Run Unit Tests with Docker Source: https://github.com/nerzal/gocloak/wiki/Contribute Start a Keycloak instance in Docker for running unit tests. Ensure the realm JSON is mounted and ports are exposed. ```shell $ docker run -d -e KEYCLOAK_USER=admin -e KEYCLOAK_PASSWORD=secret -e KEYCLOAK_IMPORT=/tmp/gocloak-realm.json -v "`pwd`/testdata/gocloak-realm.json:/tmp/gocloak-realm.json" -p 8080:8080 --name keycloak quay.io/keycloak/keycloak -Dkeycloak.profile.feature.upload_scripts=enabled $ go test -race PASS ok github.com/Nerzal/gocloak/v4 24.513s ``` -------------------------------- ### GetKeyStoreConfig Source: https://github.com/nerzal/gocloak/blob/main/_autodocs/api-reference/server-info-and-identity-providers.md Gets the keystore configuration for a realm (active keys and key list). ```APIDOC ## GetKeyStoreConfig ### Description Gets the keystore configuration for a realm (active keys and key list). ### Method Signature ```go func (g *GoCloak) GetKeyStoreConfig(ctx context.Context, token, realm string) (*KeyStoreConfig, error) ``` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Returns - `*KeyStoreConfig`: Keystore configuration with active keys. - `error`: An error if the request fails. ``` -------------------------------- ### Get Client Roles Source: https://github.com/nerzal/gocloak/blob/main/_autodocs/api-reference/clients-management.md Lists all available roles for a given client. Requires context, admin token, realm name, client ID, and query parameters. ```go func (g *GoCloak) GetClientRoles(ctx context.Context, token, realm, idOfClient string, params GetRoleParams) ([]*Role, error) ``` -------------------------------- ### Get All Client Scopes Source: https://github.com/nerzal/gocloak/blob/main/_autodocs/api-reference/realms-and-client-scopes.md Lists all available client scopes within a realm. Requires an admin access token and the realm name. ```go func (g *GoCloak) GetClientScopes(ctx context.Context, token, realm string) ([]*ClientScope, error) ``` -------------------------------- ### Working with Tokens: Login, Refresh, Decode, Introspect Source: https://github.com/nerzal/gocloak/blob/main/_autodocs/README.md Provides examples for common token operations including logging in with username/password, refreshing an expired token, decoding claims, and introspecting a token. ```go // Login with username/password token, err := client.Login(ctx, "my-app", "secret", "realm", "user", "pass") ``` ```go // Refresh expired token newToken, err := client.RefreshToken(ctx, token.RefreshToken, "my-app", "secret", "realm") ``` ```go // Decode token claims decoded, claims, err := client.DecodeAccessToken(ctx, token.AccessToken, "realm") ``` ```go // Introspect token info, err := client.RetrospectToken(ctx, token.AccessToken, "client-id", "secret", "realm") ``` -------------------------------- ### Import gocloak Package Source: https://github.com/nerzal/gocloak/blob/main/README.md Import the gocloak package into your Go project to start using its functionalities. ```go import "github.com/Nerzal/gocloak/v14" ``` -------------------------------- ### Get Request with Basic Authentication Source: https://github.com/nerzal/gocloak/blob/main/_autodocs/api-reference/client-and-authentication.md Returns a request configured with HTTP basic authentication using client credentials. Provide your client ID and secret. ```go req := client.GetRequestWithBasicAuth(ctx, "my-client", "client-secret") ``` -------------------------------- ### Get Server Info - GoCloak Source: https://github.com/nerzal/gocloak/blob/main/_autodocs/api-reference/server-info-and-identity-providers.md Retrieves server information including version and system details. Requires an admin access token. ```go func (g *GoCloak) GetServerInfo(ctx context.Context, accessToken string) (*ServerInfoRepresentation, error) ``` ```go info, err := client.GetServerInfo(ctx, token) if err != nil { panic("Failed to get server info") } fmt.Println("Keycloak Version:", info.SystemInfo.Version) ``` -------------------------------- ### Get User Info (OpenID Connect) Source: https://github.com/nerzal/gocloak/blob/main/_autodocs/api-reference/users-management.md Retrieves OpenID Connect UserInfo for the authenticated user using their access token. Requires the realm name. ```go func (g *GoCloak) GetUserInfo(ctx context.Context, accessToken, realm string) (*UserInfo, error) ``` ```go info, err := client.GetUserInfo(ctx, userToken, "myrealm") if err != nil { log.Fatal("Failed to get user info") } fmt.Println("User:", info.Name, "Email:", info.Email) ``` -------------------------------- ### Get Resource Client Source: https://github.com/nerzal/gocloak/blob/main/_autodocs/api-reference/authorization-and-events.md Retrieves a specific resource using the client's access token. Requires context, token, realm, and the resource ID. ```go func (g *GoCloak) GetResourceClient(ctx context.Context, token, realm, resourceID string) (*ResourceRepresentation, error) ``` -------------------------------- ### Get bumptag Help Information Source: https://github.com/nerzal/gocloak/wiki/Contribute Display the help message for the bumptag tool, which is used for version bumping and tag creation. ```shell $ bumptag --help Usage: bumptag [] The name of the tag to create, must be Semantic Versions 2.0.0 (http://semver.org) -e, --edit Edit an annotation -r, --dry-run Prints an annotation for the new tag -s, --silent Do not show the created tag -a, --auto-push Push the created tag automatically -m, --major Increment the MAJOR version -n, --minor Increment the MINOR version (default) -p, --patch Increment the PATCH version --version Show a version of the bumptag tool --find-tag Show the last tag, can be useful for CI tools ``` -------------------------------- ### Get All Clients in Realm Source: https://github.com/nerzal/gocloak/blob/main/examples/ADD_CLIENT_ROLE_TO_USER.md Fetches all clients within the current realm and returns them as a map keyed by their client ID. This is useful for validating client existence. ```go func (tkc *Tkc) getClients(ctx context.Context) (clients map[string]gocloak.Client, getErr error) { var clientList []*gocloak.Client // init map clients = make(map[string]gocloak.Client) // get all clients of realm if clientList, getErr = tkc.client.GetClients(ctx, tkc.token.AccessToken, tkc.realm, gocloak.GetClientsParams{}); getErr != nil { getErr = fmt.Errorf("get clients of realm failed (error: %s)", getErr.Error()) return clients, getErr } // transform to map with clientID as map key for _, c := range clientList { clients[*c.ClientID] = *c } return clients, nil } ``` -------------------------------- ### Create and Configure a User in Go Source: https://github.com/nerzal/gocloak/blob/main/_autodocs/00-START-HERE.md Use this pattern to create a new user, set their password, and add them to a group. Ensure the realm and group ID are correctly specified. ```go user := gocloak.User{ Username: gocloak.StringP("john.doe"), Email: gocloak.StringP("john@example.com"), Enabled: gocloak.BoolP(true), } userID, _ := client.CreateUser(ctx, token, "realm", user) client.SetPassword(ctx, token, userID, "realm", "Pass123!", false) client.AddUserToGroup(ctx, token, "realm", userID, groupID) ``` -------------------------------- ### GetClientRepresentation Go Example Source: https://github.com/nerzal/gocloak/blob/main/_autodocs/api-reference/clients-management.md Retrieves a client's full representation, including its secret, by its clientId. This is useful when you need all client details. Ensure you have an admin access token and the realm name. ```go client, err := client.GetClientRepresentation(ctx, token, "myrealm", "my-app") if err != nil { log.Fatal("Client not found") } fmt.Println("Client name:", client.Name) ``` -------------------------------- ### Get Clients Default Scopes Source: https://github.com/nerzal/gocloak/blob/main/_autodocs/api-reference/clients-management.md Gets the list of default client scopes assigned to a client. Requires an admin access token and the client's internal ID. ```go func (g *GoCloak) GetClientsDefaultScopes(ctx context.Context, token, realm, idOfClient string) ([]*ClientScope, error) ``` -------------------------------- ### User Provisioning with GoCloak Source: https://github.com/nerzal/gocloak/blob/main/_autodocs/README.md Demonstrates creating a user, setting their password, assigning a default group, granting roles, and triggering email actions for verification and password updates. ```go // Create and configure user user := gocloak.User{ Username: gocloak.StringP("newuser"), Email: gocloak.StringP("user@example.com"), Enabled: gocloak.BoolP(true), } userID, _ := client.CreateUser(ctx, token, "realm", user) // Set password client.SetPassword(ctx, token, userID, "realm", "TempPass123!", true) // Assign default group client.AddUserToGroup(ctx, token, "realm", userID, defaultGroupID) // Assign roles roles := []gocloak.Role{{Name: gocloak.StringP("user")}} client.AddRealmRoleToUser(ctx, token, "realm", userID, roles) // Send email action client.ExecuteActionsEmail(ctx, token, "realm", gocloak.ExecuteActionsEmail{ UserID: gocloak.StringP(userID), Lifespan: gocloak.IntP(3600), Actions: []string{"VERIFY_EMAIL", "UPDATE_PASSWORD"}, }) ``` -------------------------------- ### Get Realm Roles By User ID Go Source: https://github.com/nerzal/gocloak/blob/main/_autodocs/api-reference/users-management.md Gets all realm-level roles assigned to a user. Requires context, admin token, realm name, and user ID. ```go func (g *GoCloak) GetRealmRolesByUserID(ctx context.Context, token, realm, userID string) ([]*Role, error) ``` -------------------------------- ### GetRequestingPartyPermissionDecision Source: https://github.com/nerzal/gocloak/blob/main/_autodocs/api-reference/client-and-authentication.md Gets a decision on requested permissions from the server. ```APIDOC ## GetRequestingPartyPermissionDecision ### Description Gets a decision on requested permissions from the server. ### Method Signature ```go func (g *GoCloak) GetRequestingPartyPermissionDecision(ctx context.Context, token, realm string, options RequestingPartyTokenOptions) (*RequestingPartyPermissionDecision, error) ``` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Parameters Table | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | ctx | context.Context | Yes | Request context | | token | string | Yes | User's token | | realm | string | Yes | Realm name | | options | RequestingPartyTokenOptions | Yes | Request options | ### Returns - `(*RequestingPartyPermissionDecision, error)` — Permission decision. ``` -------------------------------- ### GetRealmRolesByUserID Source: https://github.com/nerzal/gocloak/blob/main/_autodocs/api-reference/users-management.md Gets all realm-level roles assigned to a user. ```APIDOC ## GetRealmRolesByUserID ### Description Gets all realm-level roles assigned to a user. ### Method (Not specified, likely a Go function call) ### Parameters #### Path Parameters (None specified) #### Query Parameters (None specified) #### Request Body (None specified) ### Request Example (Not specified) ### Response #### Success Response - `[]*Role` — List of assigned roles. #### Response Example (Not specified) ``` -------------------------------- ### GetClientsOptionalScopes Source: https://github.com/nerzal/gocloak/blob/main/_autodocs/api-reference/clients-management.md Gets the list of optional client scopes for a client. ```APIDOC ## GetClientsOptionalScopes ### Description Gets the list of optional client scopes for a client. ### Method This is a Go SDK method call. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Response #### Success Response - **ClientScope** ([]*ClientScope) - List of optional scopes. #### Response Example ```json [ { "id": "optional-scope-id-1", "name": "optional-scope-1", "description": "First optional scope" } ] ``` ``` -------------------------------- ### GetUserBruteForceDetectionStatus Source: https://github.com/nerzal/gocloak/blob/main/_autodocs/api-reference/users-management.md Gets the brute force protection status for a user. ```APIDOC ## GetUserBruteForceDetectionStatus ### Description Gets the brute force protection status for a user. ### Method Not specified (Go function signature provided) ### Endpoint Not specified (Go function signature provided) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response - **BruteForceStatus** (*BruteForceStatus*) - Brute force status details. #### Response Example None ``` -------------------------------- ### GetClients Go Example with Filtering Source: https://github.com/nerzal/gocloak/blob/main/_autodocs/api-reference/clients-management.md Lists clients in a realm, allowing filtering by clientId. Use this when you need to retrieve a list of clients based on specific criteria. Ensure you have an admin access token and the realm name. ```go params := gocloak.GetClientsParams{ ClientID: gocloak.StringP("my-app"), } clients, err := client.GetClients(ctx, token, "myrealm", params) ``` -------------------------------- ### Managing Users: Create, Get, Set Password, Assign Role Source: https://github.com/nerzal/gocloak/blob/main/_autodocs/README.md Illustrates how to manage users in Keycloak, including creating a new user, retrieving a list of users with parameters, setting a user's password, and assigning a role to a user. ```go // Create user user := gocloak.User{ Username: gocloak.StringP("john.doe"), Email: gocloak.StringP("john@example.com"), Enabled: gocloak.BoolP(true), } userID, err := client.CreateUser(ctx, token, "realm", user) ``` ```go // Get all users params := gocloak.GetUsersParams{ Max: gocloak.IntP(100), } users, err := client.GetUsers(ctx, token, "realm", params) ``` ```go // Set password err = client.SetPassword(ctx, token, userID, "realm", "newpassword", false) ``` ```go // Assign role roles := []gocloak.Role{{Name: gocloak.StringP("admin")}} ``` ```go err = client.AddRealmRoleToUser(ctx, token, "realm", userID, roles) ``` -------------------------------- ### GetClientsDefaultScopes Source: https://github.com/nerzal/gocloak/blob/main/_autodocs/api-reference/clients-management.md Gets the list of default client scopes assigned to a client. ```APIDOC ## GetClientsDefaultScopes ### Description Gets the list of default client scopes assigned to a client. ### Method This is a Go SDK method call. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Response #### Success Response - **ClientScope** ([]*ClientScope) - List of default scopes. #### Response Example ```json [ { "id": "scope-id-1", "name": "default-scope-1", "description": "First default scope" }, { "id": "scope-id-2", "name": "default-scope-2", "description": "Second default scope" } ] ``` ``` -------------------------------- ### GetClientRolesByUserID Source: https://github.com/nerzal/gocloak/blob/main/_autodocs/api-reference/users-management.md Gets all client-level roles assigned to a user for a specific client. ```APIDOC ## GetClientRolesByUserID ### Description Gets all client-level roles assigned to a user for a specific client. ### Method (Not specified, likely a Go function call) ### Parameters #### Path Parameters (None specified) #### Query Parameters (None specified) #### Request Body (None specified) ### Request Example (Not specified) ### Response #### Success Response - `[]*Role` — List of client roles. #### Response Example (Not specified) ``` -------------------------------- ### Managing Groups: Create, Add User, List Members Source: https://github.com/nerzal/gocloak/blob/main/_autodocs/README.md Shows how to manage groups in Keycloak, including creating a new group, adding a user to a group, and retrieving a list of group members. ```go // Create group group := gocloak.Group{ Name: gocloak.StringP("developers"), } groupID, err := client.CreateGroup(ctx, token, "realm", group) ``` ```go // Add user to group err = client.AddUserToGroup(ctx, token, "realm", userID, groupID) ``` ```go // List group members members, err := client.GetGroupMembers(ctx, token, "realm", groupID, params) ``` -------------------------------- ### GetIssuer Source: https://github.com/nerzal/gocloak/blob/main/_autodocs/api-reference/server-info-and-identity-providers.md Gets the issuer of the given realm (OpenID Connect metadata). ```APIDOC ## GetIssuer ### Description Gets the issuer of the given realm (OpenID Connect metadata). ### Method Signature ```go func (g *GoCloak) GetIssuer(ctx context.Context, realm string) (*IssuerResponse, error) ``` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Returns - `*IssuerResponse`: Issuer information. - `error`: An error if the request fails. ### Example ```go issuer, err := client.GetIssuer(ctx, "myrealm") if err != nil { panic("Failed to get issuer") } fmt.Println("Issuer:", issuer.Realm) fmt.Println("Public Key:", issuer.PublicKey) ``` ``` -------------------------------- ### Load Configuration from Environment Variables Source: https://github.com/nerzal/gocloak/blob/main/_autodocs/configuration.md Load Keycloak URL, admin credentials, and realm from environment variables. Provides default for KEYCLOAK_URL if not set. ```go import "os" func setupKeycloakClient() (*gocloak.GoCloak, error) { baseURL := os.Getenv("KEYCLOAK_URL") if baseURL == "" { baseURL = "https://keycloak.example.com" } return gocloak.NewClient(baseURL), nil } func authenticateAdmin(ctx context.Context, client *gocloak.GoCloak) (*gocloak.JWT, error) { username := os.Getenv("KEYCLOAK_ADMIN_USERNAME") password := os.Getenv("KEYCLOAK_ADMIN_PASSWORD") realm := os.Getenv("KEYCLOAK_REALM") return client.LoginAdmin(ctx, username, password, realm) } ``` -------------------------------- ### Import Identity Provider Config From File Source: https://github.com/nerzal/gocloak/blob/main/_autodocs/api-reference/server-info-and-identity-providers.md Parses identity provider configuration from an uploaded file. Use this to import settings like SAML metadata. ```go func (g *GoCloak) ImportIdentityProviderConfigFromFile(ctx context.Context, token, realm, providerID, fileName string, fileBody io.Reader) (map[string]string, error) ``` ```go file, _ := os.Open("saml-metadata.xml") defer file.Close() config, err := client.ImportIdentityProviderConfigFromFile(ctx, token, "myrealm", "saml", "metadata.xml", file) ``` -------------------------------- ### Get Identity Provider Source: https://github.com/nerzal/gocloak/blob/main/_autodocs/api-reference/server-info-and-identity-providers.md Retrieves the configuration for a specific identity provider by its alias. ```APIDOC ## GetIdentityProvider ### Description Retrieves a specific identity provider by alias. ### Method GET (Assumed based on retrieval operation) ### Endpoint `/admin/realms/{realm}/identity-provider/instances/{alias}` (Assumed based on typical REST patterns for resource retrieval) ### Parameters #### Path Parameters - **realm** (string) - Required - Realm name - **alias** (string) - Required - Provider alias (e.g., "google") ### Response #### Success Response (200 OK) - **IdentityProviderRepresentation** - Provider configuration. #### Response Example (No explicit response example provided in source, but would be a JSON object representing the IdentityProviderRepresentation) ``` -------------------------------- ### Create Resource Client Source: https://github.com/nerzal/gocloak/blob/main/_autodocs/api-reference/authorization-and-events.md Creates a resource using the client's own access token. Requires context, token, realm, and resource representation. ```go func (g *GoCloak) CreateResourceClient(ctx context.Context, token, realm string, resource ResourceRepresentation) (*ResourceRepresentation, error) ``` -------------------------------- ### Get Identity Providers Source: https://github.com/nerzal/gocloak/blob/main/_autodocs/api-reference/server-info-and-identity-providers.md Lists all identity providers configured in the specified realm. ```APIDOC ## GetIdentityProviders ### Description Lists all identity providers in the realm. ### Method GET (Assumed based on retrieval operation) ### Endpoint `/admin/realms/{realm}/identity-provider/instances` (Assumed based on typical REST patterns for resource listing) ### Parameters #### Path Parameters - **realm** (string) - Required - Realm name ### Request Example ```go providers, err := client.GetIdentityProviders(ctx, token, "myrealm") for _, provider := range providers { fmt.Println("Provider:", *provider.Alias) } ``` ### Response #### Success Response (200 OK) - **[]*IdentityProviderRepresentation** - List of providers. #### Response Example (No explicit response example provided in source, but would be a JSON array of IdentityProviderRepresentation objects) ``` -------------------------------- ### GetComponents Go Function Source: https://github.com/nerzal/gocloak/blob/main/_autodocs/api-reference/server-info-and-identity-providers.md Use this function to list all components configured in a given realm. Requires an admin access token. ```go func (g *GoCloak) GetComponents(ctx context.Context, token, realm string) ([]*Component, error) ``` -------------------------------- ### GetAdapterConfiguration Source: https://github.com/nerzal/gocloak/blob/main/_autodocs/api-reference/clients-management.md Retrieves the adapter configuration for a specific client, useful for client library setup. ```APIDOC ## GetAdapterConfiguration ### Description Gets the adapter configuration for a client (for client library configuration). ### Method Not specified (likely a Go SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response - **AdapterConfiguration** (*object*) - Client adapter configuration. #### Response Example None ``` -------------------------------- ### GetUserCount Source: https://github.com/nerzal/gocloak/blob/main/_autodocs/api-reference/users-management.md Gets the count of users matching the specified criteria. Uses the same filtering parameters as GetUsers. ```APIDOC ## GetUserCount ### Description Gets the count of users matching the specified criteria. ### Method GET (Assumed based on retrieval operation) ### Endpoint `/admin/realms/{realm}/users/count` (Assumed based on typical REST patterns) ### Parameters #### Path Parameters - **realm** (string) - Required - Realm name #### Query Parameters - **BriefRepresentation** (*bool) - Return only essential fields (username, ID, email) - **Email** (*string) - Filter by exact email - **EmailVerified** (*bool) - Filter by email verification status - **Enabled** (*bool) - Filter by enabled status - **Exact** (*bool) - Exact match on search fields - **First** (*int) - First result offset for pagination - **FirstName** (*string) - Filter by first name - **IDPAlias** (*string) - Filter by identity provider alias - **IDPUserID** (*string) - Filter by identity provider user ID - **LastName** (*string) - Filter by last name - **Max** (*int) - Maximum results per page - **Q** (*string) - Search query string - **Search** (*string) - Free-text search across name and email - **Username** (*string) - Filter by username ### Request Example ```go params := gocloak.GetUsersParams{ Enabled: gocloak.BoolP(true), } count, err := client.GetUserCount(ctx, token, "myrealm", params) ``` ### Response #### Success Response (200 OK) - **count** (int) - The number of users matching the criteria. #### Response Example ```json { "count": 150 } ``` ``` -------------------------------- ### Authenticate with Username/Password in Go Source: https://github.com/nerzal/gocloak/blob/main/_autodocs/00-START-HERE.md This snippet shows how to authenticate a user using their username and password to obtain an access token. It also demonstrates fetching users with specific parameters. ```go token, _ := client.Login(ctx, "app-id", "secret", "realm", "user", "pass") users, _ := client.GetUsers(ctx, token.AccessToken, "realm", params) ``` -------------------------------- ### Get Unauthenticated Request Source: https://github.com/nerzal/gocloak/blob/main/_autodocs/api-reference/client-and-authentication.md Returns a basic request object configured with context for making unauthenticated calls. ```go req := client.GetRequest(context.Background()) ``` -------------------------------- ### Create New User with gocloak Source: https://github.com/nerzal/gocloak/blob/main/README.md This snippet demonstrates how to create a new user in Keycloak. Ensure you have valid admin credentials and the correct Keycloak instance URL and realm name. ```go client := gocloak.NewClient("https://mycool.keycloak.instance") ctx := context.Background() token, err := client.LoginAdmin(ctx, "user", "password", "realmName") if err != nil { panic("Something wrong with the credentials or url") } user := gocloak.User{ FirstName: gocloak.StringP("Bob"), LastName: gocloak.StringP("Uncle"), Email: gocloak.StringP("something@really.wrong"), Enabled: gocloak.BoolP(true), Username: gocloak.StringP("CoolGuy"), } _, err = client.CreateUser(ctx, token.AccessToken, "realm", user) if err != nil { panic("Oh no!, failed to create user :(") } ``` -------------------------------- ### Get Realm Configuration Source: https://github.com/nerzal/gocloak/blob/main/_autodocs/api-reference/realms-and-client-scopes.md Retrieves the configuration of a specific realm using its name. Requires an admin access token. ```go func (g *GoCloak) GetRealm(ctx context.Context, token, realm string) (*RealmRepresentation, error) ``` ```go realmConfig, err := client.GetRealm(ctx, token, "myrealm") if err != nil { panic("Realm not found") } fmt.Println("Realm enabled:", realmConfig.Enabled) ``` -------------------------------- ### Create an OAuth Client in Go Source: https://github.com/nerzal/gocloak/blob/main/_autodocs/00-START-HERE.md Use this pattern to programmatically create a new OAuth client within a specified realm. Remember to provide valid redirect URIs for your application. ```go client := gocloak.Client{ ClientID: gocloak.StringP("my-app"), RedirectURIs: []string{"https://app.example.com/callback"}, } clientID, _ := client.CreateClient(ctx, token, "realm", client) ``` -------------------------------- ### Get User Credentials Source: https://github.com/nerzal/gocloak/blob/main/_autodocs/api-reference/users-management.md Retrieves all credentials associated with a specific user in a given realm. Requires an admin access token. ```go func (g *GoCloak) GetCredentials(ctx context.Context, token, realm, userID string) ([]*CredentialRepresentation, error) ``` -------------------------------- ### Handle Resource Not Found Errors (404) Source: https://github.com/nerzal/gocloak/blob/main/_autodocs/errors.md Indicates a requested resource does not exist. Verify resource IDs using list operations and handle 404 gracefully. ```go user, err := client.GetUserByID(ctx, token, "myrealm", "non-existent") if err != nil { // HTTP 404 Not Found // Error message: "User not found" } ``` -------------------------------- ### Get Identity Provider Mappers Source: https://github.com/nerzal/gocloak/blob/main/_autodocs/api-reference/server-info-and-identity-providers.md Lists all mappers associated with a specific identity provider. Requires realm and provider alias. ```go func (g *GoCloak) GetIdentityProviderMappers(ctx context.Context, token, realm, alias string) ([]*IdentityProviderMapper, error) ``` -------------------------------- ### Initialize GoCloak Client Source: https://github.com/nerzal/gocloak/blob/main/_autodocs/configuration.md Basic initialization of the GoCloak client requires the base URL of the Keycloak server. Ensure the URL includes the protocol (http/https). ```go client := gocloak.NewClient("https://keycloak.example.com") ``` -------------------------------- ### CreateRealm Source: https://github.com/nerzal/gocloak/blob/main/_autodocs/api-reference/realms-and-client-scopes.md Creates a new realm with the provided configuration. Requires an admin access token from the master realm. ```APIDOC ## CreateRealm ### Description Creates a new realm. ### Method POST ### Endpoint /admin/realms ### Parameters #### Query Parameters - **token** (string) - Required - Admin access token (from master realm). #### Request Body - **realm** (RealmRepresentation) - Required - Realm configuration. ### Request Example ```go newRealm := gocloak.RealmRepresentation{ Realm: gocloak.StringP("newrealm"), Enabled: gocloak.BoolP(true), DisplayName: gocloak.StringP("New Realm"), } realmID, err := client.CreateRealm(ctx, token, newRealm) ``` ### Response #### Success Response (201) - **string** - Realm name/ID. #### Response Example ```json "newrealm" ``` ``` -------------------------------- ### GetClientScopesScopeMappingsClientRoles Source: https://github.com/nerzal/gocloak/blob/main/_autodocs/api-reference/realms-and-client-scopes.md Gets client roles attached to a client scope. This retrieves all client roles that are currently associated with a specific client scope. ```APIDOC ## GetClientScopesScopeMappingsClientRoles ### Description Gets client roles attached to a client scope. ### Method (Not specified, likely a GET request) ### Endpoint (Not specified) ### Parameters #### Path Parameters - **realm** (string) - Required - Realm name - **idOfClientScope** (string) - Required - Client scope ID - **idOfClient** (string) - Required - Target client #### Query Parameters (None specified) #### Request Body (None specified) ### Request Example (Not specified) ### Response #### Success Response (200) - **roles** ([]*Role) - Attached client roles. #### Response Example (Not specified) ERROR HANDLING: - Returns a list of attached client roles and an error if the operation fails. ``` -------------------------------- ### Client Initialization and Authentication Source: https://github.com/nerzal/gocloak/blob/main/_autodocs/INDEX.md Functions for creating a GoCloak client instance and handling various authentication flows, including login, token management, and logout. ```APIDOC ## Client Initialization ### Description Creates a new GoCloak client instance. ### Method `NewClient` ### Endpoint N/A (SDK function) ### Parameters None ### Request Example ```go client := gocloak.NewClient("http://localhost:8080") ``` ### Response - **client** (*gocloak.GoCloak*) - An initialized GoCloak client instance. ## Authentication Methods ### Description Provides functions for various authentication scenarios, including admin login, client login, user login, OTP, signed JWT, and token exchange. ### Methods - `LoginAdmin` - `LoginClient` - `Login` - `LoginOtp` - `LoginClientSignedJWT` - `LoginClientTokenExchange` ### Endpoint N/A (SDK functions) ### Parameters Refer to individual function documentation for specific parameters. ### Request Example ```go // Example for LoginAdmin token, err := client.LoginAdmin(ctx, "admin-user", "admin-password", "master") ``` ### Response - **token** (**gocloak. பொருட்க*) - Authentication token object. - **err** (*error*) - Error if the authentication fails. ## Token Management ### Description Functions for managing authentication tokens, including retrieving, refreshing, introspecting, and revoking tokens. ### Methods - `GetToken` - `RefreshToken` - `RetrospectToken` - `RevokeToken` - `DecodeAccessToken` ### Endpoint N/A (SDK functions) ### Parameters Refer to individual function documentation for specific parameters. ### Request Example ```go // Example for RefreshToken newToken, err := client.RefreshToken(ctx, token.RefreshToken, "master") ``` ### Response - **token** (**gocloak. பொருட்க*) - Token object. - **err** (*error*) - Error if the operation fails. ## Logout ### Description Functions for logging out users and clients, including revoking sessions and consents. ### Methods - `Logout` - `LogoutPublicClient` - `LogoutAllSessions` - `LogoutUserSession` - `RevokeUserConsents` ### Endpoint N/A (SDK functions) ### Parameters Refer to individual function documentation for specific parameters. ### Request Example ```go // Example for Logout err := client.Logout(ctx, "your-realm", "your-session-id") ``` ### Response - **err** (*error*) - Error if the logout fails. ``` -------------------------------- ### GetClientScopesScopeMappingsRealmRolesAvailable Source: https://github.com/nerzal/gocloak/blob/main/_autodocs/api-reference/realms-and-client-scopes.md Gets available realm roles for a client scope. This operation lists all realm roles that can potentially be assigned to a client scope. ```APIDOC ## GetClientScopesScopeMappingsRealmRolesAvailable ### Description Gets available realm roles for a client scope. ### Method (Not specified, likely a GET request) ### Endpoint (Not specified) ### Parameters #### Path Parameters - **realm** (string) - Required - Realm name - **clientScopeID** (string) - Required - Client scope ID #### Query Parameters (None specified) #### Request Body (None specified) ### Request Example (Not specified) ### Response #### Success Response (200) - **roles** ([]*Role) - Available roles. #### Response Example (Not specified) ERROR HANDLING: - Returns a list of available roles and an error if the operation fails. ``` -------------------------------- ### Handle GoCloak API and Context Errors Source: https://github.com/nerzal/gocloak/blob/main/_autodocs/README.md Demonstrates how to differentiate and handle API errors (e.g., 404, 401) and context errors like timeouts when interacting with the Keycloak API. ```go user, err := client.GetUserByID(ctx, token, "realm", "user-id") if err != nil { if apiErr, ok := err.(*gocloak.APIError); ok { // HTTP error from Keycloak switch apiErr.Code { case 404: fmt.Println("User not found") case 401: fmt.Println("Unauthorized") default: fmt.Printf("Error: %s\n", apiErr.Message) } } else if errors.Is(err, context.DeadlineExceeded) { // Context timeout fmt.Println("Request timeout") } else { // Network error fmt.Println("Network error:", err) } } ``` -------------------------------- ### Components Source: https://github.com/nerzal/gocloak/blob/main/_autodocs/INDEX.md Manage server components. ```APIDOC ## CreateComponent ### Description Creates a new server component. ### Method POST ### Endpoint /components ``` ```APIDOC ## GetComponents ### Description Retrieves a list of all server components. ### Method GET ### Endpoint /components ``` ```APIDOC ## GetComponentsWithParams ### Description Retrieves a list of server components with filtering parameters. ### Method GET ### Endpoint /components ``` ```APIDOC ## GetComponent ### Description Retrieves a specific server component by its ID. ### Method GET ### Endpoint /components/{id} ``` ```APIDOC ## UpdateComponent ### Description Updates an existing server component. ### Method PUT ### Endpoint /components/{id} ``` ```APIDOC ## DeleteComponent ### Description Deletes a specific server component by its ID. ### Method DELETE ### Endpoint /components/{id} ``` -------------------------------- ### GetClientScopesScopeMappingsRealmRoles Source: https://github.com/nerzal/gocloak/blob/main/_autodocs/api-reference/realms-and-client-scopes.md Gets realm roles assigned to a client scope. This retrieves all realm roles that are currently associated with a specific client scope. ```APIDOC ## GetClientScopesScopeMappingsRealmRoles ### Description Gets realm roles assigned to a client scope (not client's scope). ### Method (Not specified, likely a GET request) ### Endpoint (Not specified) ### Parameters #### Path Parameters - **realm** (string) - Required - Realm name - **clientScopeID** (string) - Required - Client scope ID #### Query Parameters (None specified) #### Request Body (None specified) ### Request Example (Not specified) ### Response #### Success Response (200) - **roles** ([]*Role) - List of realm roles. #### Response Example (Not specified) ERROR HANDLING: - Returns a list of roles and an error if the operation fails. ``` -------------------------------- ### Create Client Role Source: https://github.com/nerzal/gocloak/blob/main/_autodocs/api-reference/clients-management.md Creates a new role for a client. Requires context, admin token, realm name, client ID, and a Role object. Returns the new role's ID. ```go func (g *GoCloak) CreateClientRole(ctx context.Context, token, realm, idOfClient string, role Role) (string, error) ``` ```go role := gocloak.Role{ Name: gocloak.StringP("editor"), Description: gocloak.StringP("Document editor role"), } roleID, err := client.CreateClientRole(ctx, token, "myrealm", "client-id", role) ``` -------------------------------- ### Get Identity Providers Go API Source: https://github.com/nerzal/gocloak/blob/main/_autodocs/api-reference/server-info-and-identity-providers.md Lists all configured identity providers within a given realm. The result is a slice of IdentityProviderRepresentation. ```go func (g *GoCloak) GetIdentityProviders(ctx context.Context, token, realm string) ([]*IdentityProviderRepresentation, error) ``` ```go providers, err := client.GetIdentityProviders(ctx, token, "myrealm") for _, provider := range providers { fmt.Println("Provider:", *provider.Alias) } ``` -------------------------------- ### Prepare Role LDAP Mapper Configuration Source: https://github.com/nerzal/gocloak/blob/main/examples/USER_FEDERATION_ROLE_LDAP_MAPPER.md Prepares a `gocloak.Component` object for a role LDAP mapper with predefined configuration settings. This includes DNs, attributes, and retrieval strategies. ```go func prepareRoleLdapMapper(name, idUserFederation string) (mapper gocloak.Component) { mapperConfig := make(map[string][]string) mapperConfig["roles.dn"] = []string{"ou=roles,dc=example,dc=com"} mapperConfig["role.name.ldap.attribute"] = []string{"cn"} mapperConfig["role.object.classes"] = []string{"group"} mapperConfig["membership.ldap.attribute"] = []string{"member"} mapperConfig["membership.attribute.type"] = []string{"DN"} mapperConfig["membership.user.ldap.attribute"] = []string{"cn"} mapperConfig["mode"] = []string{"IMPORT"} mapperConfig["user.roles.retrieve.strategy"] = []string{"LOAD_ROLES_BY_MEMBER_ATTRIBUTE"} mapperConfig["memberof.ldap.attribute"] = []string{"memberOf"} mapperConfig["use.realm.roles.mapping"] = []string{"true"} mapperConfig["client.id"] = []string{"account"} mapper = gocloak.Component{ Name: gocloak.StringP(name), ProviderID: gocloak.StringP("role-ldap-mapper"), ProviderType: gocloak.StringP("org.keycloak.storage.ldap.mappers.LDAPStorageMapper"), ParentID: gocloak.StringP(idUserFederation), ComponentConfig: &mapperConfig, } return mapper } ```