phasetwo

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 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: the organizations, members, roles, domains, identity providers, invitations, SCIM, webhooks, events and realm attributes that Phase Two adds to Keycloak. For core Keycloak administration (realms, users, clients), use a Keycloak admin client alongside it.

[!NOTE] All Phase Two SDKs (Java, TypeScript, Python, Go) share the version of the Phase Two API they implement: every SDK release X.Y.* implements API X.Y, and patch releases are SDK-only fixes. While on 0.x, a new minor version can contain breaking changes from the API spec, so pin a version.

Installation

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

Requires Go 1.26 or later.

Quick start

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. The new id is in the Location header.
name := "example"
created, err := client.CreateOrganizationWithResponse(ctx, realm, openapi.OrganizationRepresentation{Name: &name})
if err != nil {
	log.Fatal(err)
}
if err := phasetwo.Check(created.HTTPResponse, created.Body); err != nil {
	log.Fatal(err)
}
orgID, _ := phasetwo.IDFromLocation(created.HTTPResponse)

// Create a link to the IdP Wizard for the organization
link, err := client.CreatePortalLinkWithFormdataBodyWithResponse(ctx, realm, orgID, openapi.CreatePortalLinkFormdataRequestBody{})
if err != nil {
	log.Fatal(err)
}
fmt.Println(*link.JSON200.Link)

The same code is in example_test.go, which go test compiles.

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.

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, HTTPResponse and Body the raw response.
  • Operations with request bodies take a typed body (openapi.OrganizationRepresentation, ...). There's also a ...WithBodyWithResponse variant that takes an io.Reader.
  • Optional query parameters are in a *openapi.XxxParams struct. Pass nil for none.
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.

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; sdk-generator.json records the spec commit it came from. 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

Create an organization, make a link to its IdP Wizard, and send an audit event. This example is compiled but not run by `go test`.

package main

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

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

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

	client, err := phasetwo.New(ctx, phasetwo.Config{
		BaseURL:      "https://auth.example.com/auth",
		TokenRealm:   realm,
		ClientID:     "api-client",
		ClientSecret: os.Getenv("PHASETWO_CLIENT_SECRET"),
	})
	if err != nil {
		log.Fatal(err)
	}

	// 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 {
		log.Fatal(err)
	}
	if err := phasetwo.Check(created.HTTPResponse, created.Body); err != nil {
		log.Fatal(err)
	}
	orgID, _ := phasetwo.IDFromLocation(created.HTTPResponse)

	// Create a link to the IdP Wizard for the organization
	link, err := client.CreatePortalLinkWithFormdataBodyWithResponse(ctx, realm, orgID, openapi.CreatePortalLinkFormdataRequestBody{})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(*link.JSON200.Link)

	// Send an audit event
	eventType := "foo.bar"
	now := time.Now().UnixMilli()
	if _, err := client.CreateEventWithResponse(ctx, realm, openapi.EventRepresentation{Type: &eventType, Time: &now}); err != nil {
		log.Fatal(err)
	}
}

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