phasetwo

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2026 License: Apache-2.0 Imports: 10 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Phase Two Go SDK

build Go Reference license docs

📚 Documentation • 🚀 Hosted Keycloak • 🤖 Keycloak Skills • 💬 Support

[!TIP] Run this in our cloud, no setup needed. Phase Two hosts Keycloak with all of our extensions built in. Try it free with your own cluster →

Using a coding agent? Add the Phase Two Keycloak skills (launch post) to Claude Code, Cursor or Codex so your agent can set up passwordless login, SSO, organizations and clusters for you:

# Install the skills (connects to our hosted MCP server)
claude plugin marketplace add p2-inc/keycloak-skills
claude plugin install phasetwo@keycloak-skills
# Or connect to the MCP server directly
claude mcp add --transport http keycloak https://mcp.phasetwo.io/mcp

A Go client for the Phase Two Admin REST API: organizations, members, roles, domains, identity providers, invitations, SCIM, webhooks and events, realm attributes and magic links, all added to Keycloak by Phase Two. For core Keycloak administration (realms, users, clients), use a Keycloak admin client such as gocloak alongside it.

[!NOTE] Pre-1.0: minor versions can include breaking changes. All Phase Two SDKs share a version: release X.Y.* implements Phase Two API X.Y.

Installation

go get github.com/p2-inc/phasetwo-go

Requires Go 1.26 or later.

Quick start

Connect with a service account:

ctx := context.Background()
realm := "my-realm"

client, err := phasetwo.New(ctx, phasetwo.Config{
	BaseURL:      "https://auth.example.com/auth", // your Keycloak base URL
	TokenRealm:   realm,                           // where the service account lives
	ClientID:     "api-client",
	ClientSecret: os.Getenv("PHASETWO_CLIENT_SECRET"),
})
if err != nil {
	log.Fatal(err)
}

Create an organization, add a member, create an IdP Wizard link so the organization's admin can set up SSO, and send an audit event:

// Create an organization. The new id is in the Location header.
name := "example"
created, err := client.CreateOrganizationWithResponse(ctx, realm,
	openapi.OrganizationRepresentation{Name: &name})
if err != nil {
	return "", err
}
if err := phasetwo.Check(created.HTTPResponse, created.Body); err != nil {
	return "", err
}
orgID, err := phasetwo.IDFromLocation(created.HTTPResponse)
if err != nil {
	return "", err
}

// Add an existing user as a member.
added, err := client.AddOrganizationMemberWithResponse(ctx, realm, orgID, userID)
if err != nil {
	return "", err
}
if err := phasetwo.Check(added.HTTPResponse, added.Body); err != nil {
	return "", err
}

// Create a link to the IdP Wizard, so the organization's admin can set up SSO.
link, err := client.CreatePortalLinkWithFormdataBodyWithResponse(ctx, realm, orgID,
	openapi.CreatePortalLinkFormdataRequestBody{})
if err != nil {
	return "", err
}
if err := phasetwo.Check(link.HTTPResponse, link.Body); err != nil {
	return "", err
}
fmt.Println("IdP Wizard:", *link.JSON200.Link)

// Send an audit event.
eventType := "example.created"
now := time.Now().UnixMilli()
sent, err := client.CreateEventWithResponse(ctx, realm,
	openapi.EventRepresentation{Type: &eventType, Time: &now})
if err != nil {
	return "", err
}
if err := phasetwo.Check(sent.HTTPResponse, sent.Body); err != nil {
	return "", err
}

This code is in example_test.go. The integration test runs it against Phase Two Keycloak in CI.

Authentication

phasetwo.New gets tokens with the client credentials grant and refreshes them as they expire. Create a confidential client with a service account that has the roles your calls need, and pass its client id and secret in Config.

To bring your own tokens (e.g. from a login flow), set Config.TokenSource to any oauth2.TokenSource. Config.HTTPClient sets timeouts, proxies or a custom transport for both token and API requests.

Usage

  • Every operation in the API reference is a method on Client, named after its operationId, with the realm as the first argument after the context.
  • XxxWithResponse(...) returns a typed response: JSON200 (or JSON201, ...) holds the decoded body, and HTTPResponse and Body hold the raw response.
  • Operations with a request body take a typed body (openapi.OrganizationRepresentation, ...). The ...WithBodyWithResponse variant takes an io.Reader instead.
  • Optional query parameters are in an *openapi.XxxParams struct. Pass nil for none.
  • Creating a resource returns 201 Created with an empty body. Get the new id from the Location header with phasetwo.IDFromLocation(resp.HTTPResponse).
Errors

A non-2xx response is not a Go error. Check it with phasetwo.Check(resp.HTTPResponse, resp.Body), which returns a *phasetwo.APIError with the status code and body:

var apiErr *phasetwo.APIError
if errors.As(err, &apiErr) && apiErr.StatusCode == http.StatusNotFound {
	// ...
}

Compatibility

SDK Phase Two API Tested against
v0.2.x 0.2 quay.io/phasetwo/phasetwo-keycloak:26.5.6

The API version and the spec commit the SDK was generated from are in sdk-generator.json. CI tests the two latest Go releases, matching Go's own support policy.

API reference

Generated code

The openapi package is generated from the Phase Two OpenAPI spec with oapi-codegen by phasetwo-sdk-generator. Don't edit it by hand: CI regenerates it and fails if it differs. Everything in the root phasetwo package is hand-written.

go test ./...                    # unit tests
go test -tags integration ./...  # against Phase Two Keycloak in Docker

License

Apache License 2.0, see COPYING.

Documentation

Overview

Package phasetwo is a Go client for the Phase Two Admin REST API: the organizations, SSO, webhooks, events and other extensions that Phase Two adds to Keycloak.

The API operations and models are generated into the openapi package from the Phase Two OpenAPI spec. This package adds the hand-written parts: building an authenticated client (New), getting the id of a created resource (IDFromLocation) and turning error responses into errors (Check).

For core Keycloak administration (realms, users, clients), use a Keycloak admin client alongside this one.

Example

Connect with a service account, then run the quick start. This example is compiled but not run by `go test`; the integration test runs quickstart against Phase Two Keycloak.

package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"time"

	"github.com/p2-inc/phasetwo-go"
	"github.com/p2-inc/phasetwo-go/openapi"
)

// Connect with a service account, then run the quick start. This example is
// compiled but not run by `go test`; the integration test runs quickstart
// against Phase Two Keycloak.
func main() {
	// snippet:start client
	ctx := context.Background()
	realm := "my-realm"

	client, err := phasetwo.New(ctx, phasetwo.Config{
		BaseURL:      "https://auth.example.com/auth", // your Keycloak base URL
		TokenRealm:   realm,                           // where the service account lives
		ClientID:     "api-client",
		ClientSecret: os.Getenv("PHASETWO_CLIENT_SECRET"),
	})
	if err != nil {
		log.Fatal(err)
	}
	// snippet:end client

	if _, err := quickstart(ctx, client, realm, "a-user-id"); err != nil {
		log.Fatal(err)
	}
}

// quickstart creates an organization, adds a member, makes an IdP Wizard link
// for the organization and sends an audit event. It returns the organization id.
func quickstart(ctx context.Context, client *phasetwo.Client, realm, userID string) (string, error) {
	// snippet:start quickstart
	// Create an organization. The new id is in the Location header.
	name := "example"
	created, err := client.CreateOrganizationWithResponse(ctx, realm,
		openapi.OrganizationRepresentation{Name: &name})
	if err != nil {
		return "", err
	}
	if err := phasetwo.Check(created.HTTPResponse, created.Body); err != nil {
		return "", err
	}
	orgID, err := phasetwo.IDFromLocation(created.HTTPResponse)
	if err != nil {
		return "", err
	}

	// Add an existing user as a member.
	added, err := client.AddOrganizationMemberWithResponse(ctx, realm, orgID, userID)
	if err != nil {
		return "", err
	}
	if err := phasetwo.Check(added.HTTPResponse, added.Body); err != nil {
		return "", err
	}

	// Create a link to the IdP Wizard, so the organization's admin can set up SSO.
	link, err := client.CreatePortalLinkWithFormdataBodyWithResponse(ctx, realm, orgID,
		openapi.CreatePortalLinkFormdataRequestBody{})
	if err != nil {
		return "", err
	}
	if err := phasetwo.Check(link.HTTPResponse, link.Body); err != nil {
		return "", err
	}
	fmt.Println("IdP Wizard:", *link.JSON200.Link)

	// Send an audit event.
	eventType := "example.created"
	now := time.Now().UnixMilli()
	sent, err := client.CreateEventWithResponse(ctx, realm,
		openapi.EventRepresentation{Type: &eventType, Time: &now})
	if err != nil {
		return "", err
	}
	if err := phasetwo.Check(sent.HTTPResponse, sent.Body); err != nil {
		return "", err
	}
	// snippet:end quickstart
	return orgID, nil
}

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Check

func Check(resp *http.Response, body []byte) error

Check returns an *APIError if resp isn't a 2xx response. Pass the HTTPResponse and Body fields of any ...WithResponse result:

resp, err := client.GetOrganizationByIdWithResponse(ctx, realm, id)
if err != nil { ... }
if err := phasetwo.Check(resp.HTTPResponse, resp.Body); err != nil { ... }

func IDFromLocation

func IDFromLocation(resp *http.Response) (string, error)

IDFromLocation returns the id of a resource the API just created: the last path segment of the response's Location header. Create operations return 201 with an empty body, so this is how to get the new id:

resp, err := client.CreateOrganizationWithResponse(ctx, realm, org)
...
id, err := phasetwo.IDFromLocation(resp.HTTPResponse)

Types

type APIError

type APIError struct {
	StatusCode int
	// Body is the raw response body; Keycloak usually sends {"error": "..."} JSON.
	Body []byte
}

APIError is an error response from the Phase Two API.

func (*APIError) Error

func (e *APIError) Error() string

type Client

type Client struct {
	*openapi.ClientWithResponses
}

Client is an authenticated Phase Two API client. All API operations are methods of the embedded openapi.ClientWithResponses; every operation takes the realm name as its first argument after the context.

func New

func New(ctx context.Context, cfg Config) (*Client, error)

New returns a Client that adds a bearer token to every request and refreshes it when it expires.

type Config

type Config struct {
	// BaseURL is your Keycloak base URL, including the context path if it has one,
	// e.g. "https://auth.example.com/auth". Required.
	BaseURL string

	// TokenRealm, ClientID and ClientSecret get tokens with the client credentials
	// grant from TokenRealm's token endpoint, typically a service account in the
	// realm you manage. Ignored when TokenSource is set.
	TokenRealm   string
	ClientID     string
	ClientSecret string

	// TokenSource supplies access tokens instead of the client credentials grant,
	// e.g. a token from your own login flow.
	TokenSource oauth2.TokenSource

	// HTTPClient is used for both token and API requests (timeouts, proxies,
	// custom transports). Defaults to http.DefaultClient.
	HTTPClient *http.Client

	// UserAgent is sent on API requests. Defaults to "phasetwo-go".
	UserAgent string
}

Config configures a Client.

Directories

Path Synopsis
Package openapi provides primitives to interact with the openapi HTTP API.
Package openapi provides primitives to interact with the openapi HTTP API.

Jump to

Keyboard shortcuts

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