keycloak

package module
v2.0.3 Latest Latest
Warning

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

Go to latest
Published: Apr 11, 2023 License: MIT Imports: 10 Imported by: 0

README

keycloak

ci codeql Go Reference Go Report Card Total alerts

keycloak is a Go client library for accessing the Keycloak API.

Installation

go get github.com/BlueIcarus/keycloak/v2

Usage

package main

import (
    "context"

    "github.com/BlueIcarus/keycloak/v2"
    "golang.org/x/oauth2"
)

func main() {
    // create your oauth configuration
    config := oauth2.Config{
        ClientID: "admin-cli",
        Endpoint: oauth2.Endpoint{
            TokenURL: "http://localhost:8080/realms/master/protocol/openid-connect/token",
        },
    }

    // get a valid token from keycloak
    ctx := context.Background()
    token, err := config.PasswordCredentialsToken(ctx, "admin", "admin")
    if err != nil {
        panic(err)
    }

    // create a new http client that uses the token on every request
    client := config.Client(ctx, token)

    // create a new keycloak instance and provide the http client
    k, err := keycloak.NewKeycloak(client, "http://localhost:8080/")
    if err != nil {
        panic(err)
    }

    // start using the library and, for example, create a new realm
    realm := &keycloak.Realm{
        Enabled: keycloak.Bool(true),
        ID:      keycloak.String("myrealm"),
        Realm:   keycloak.String("myrealm"),
    }

    res, err := k.Realms.Create(ctx, realm)
    if err != nil {
        panic(err)
    }
}

Examples

Development

Use docker-compose to start Keycloak locally.

docker-compose up -d

Keycloak is running at http://localhost:8080/. The admin credentials are admin (username) and admin (password). If you want to change them simply edit the docker-compose.yml.

Keycloak uses PostgreSQL and all data is kept across restarts.

Use down if you want to stop the Keycloak server.

docker-compose down

Architecture

The main entry point is keycloak.go. This is where the Keycloak instance is created. It all starts in this file.

Within Keycloak we also have the concept of clients. They are the ones that connect to Keycloak for authentication and authorization purposes, e.g. our frontend and backend apps. That is why this library simply uses the keycloak instance of type Keycloak and not a client instance like go-github. Although technically this library is a Keycloak client library for Go. However this distinction should make it clear what is meant when we talk about a client in our context.

Testing

You need to have Keycloak running on your local machine to execute the tests. Simply use docker-compose to start it.

All tests are independent from each other. Before each test we create a realm and after each test we delete it. You don't have to worry about it since the helper function createRealm does that automatically for you. Inside this realm you can do whatever you want. You don't have to clean up after yourself since everything is deleted automatically when the realm is deleted.

Run all tests.

go test -race -v ./...

Create code coverage.

go test -v ./... -coverprofile=coverage.out
go tool cover -html=coverage.out -o coverage.html

We have also provided a simple Makefile that run both jobs automatically.

make

Open coverage.html with your browser.

Design goals

  1. Zero dependencies

    It's just the Go standard library.

    The only exception is go-querystring to easily handle query parameters.

  2. Idiomatic Go

    Modelled after go-github and go-jira.

  3. Keep authentication outside this library

    This is the major difference to most of the other Go Keycloak libraries.

    We leverage the brilliant oauth2 package to deal with authentication. We have provided multiple examples to show you the workflow. It basically means we do not provide any methods to call the /token endpoint.

  4. Return struct and HTTP response

    Whenever the Keycloak API returns JSON content you'll get a proper struct as well as the HTTP response.

    func (s *ClientsService) Get(ctx context.Context, realm, id string) (*Client, *http.Response, error)
    

License

MIT

Documentation

Overview

Package keycloak provides a client for using the Keycloak API.

Example (Full)
package main

import (
	"context"
	"fmt"
	"net/http"
	"net/url"
	"strings"

	"github.com/BlueIcarus/keycloak/v2"
	"golang.org/x/oauth2"
	"golang.org/x/oauth2/clientcredentials"
)

const (
	realm    = "gorealm"
	clientID = "goclient"
)

func main() {
	// create a new config for the "admin-cli" client
	config := oauth2.Config{
		ClientID: "admin-cli",
		Endpoint: oauth2.Endpoint{
			TokenURL: "http://localhost:8080/realms/master/protocol/openid-connect/token",
		},
		Scopes: []string{"openid"},
	}

	ctx := context.Background()

	// get a token
	token, err := config.PasswordCredentialsToken(ctx, "admin", "admin")
	if err != nil {
		panic(err)
	}

	// use the token on every http request
	httpClient := config.Client(ctx, token)

	// create a new keycloak client instance
	kc, err := keycloak.NewKeycloak(httpClient, "http://localhost:8080/")
	if err != nil {
		panic(err)
	}

	// create a new realm
	r := &keycloak.Realm{
		Enabled: keycloak.Bool(true),
		ID:      keycloak.String(realm),
		Realm:   keycloak.String(realm),
	}

	if _, err := kc.Realms.Create(ctx, r); err != nil {
		panic(err)
	}

	// clean up
	// remove this or comment out to keep the realm and play around in the keycloak gui
	defer func() {
		if _, err := kc.Realms.Delete(ctx, realm); err != nil {
			panic(err)
		}
	}()

	// create client
	client := &keycloak.Client{
		Enabled:  keycloak.Bool(true),
		ClientID: keycloak.String(clientID),
		Protocol: keycloak.String("openid-connect"),
	}

	res, err := kc.Clients.Create(ctx, realm, client)
	if err != nil {
		panic(err)
	}

	parts := strings.Split(res.Header.Get("Location"), "/")
	id := parts[len(parts)-1]

	// get the client to have all properties
	client, res, err = kc.Clients.Get(ctx, realm, id)
	if err != nil {
		panic(err)
	}

	// update client and enable authorization services
	client.RedirectUris = []string{"http://localhost:4200/*"}
	client.AuthorizationServicesEnabled = keycloak.Bool(true)
	client.ServiceAccountsEnabled = keycloak.Bool(true)
	client.PublicClient = keycloak.Bool(false)

	res, err = kc.Clients.Update(ctx, realm, client)
	if err != nil {
		panic(err)
	}

	// create user
	userA := &keycloak.User{
		Enabled:  keycloak.Bool(true),
		Username: keycloak.String("user_a"),
	}

	res, err = kc.Users.Create(ctx, realm, userA)
	if err != nil {
		panic(err)
	}

	parts = strings.Split(res.Header.Get("Location"), "/")
	userA.ID = &parts[len(parts)-1]

	// set password for user_a
	res, err = kc.Users.ResetPassword(ctx, realm, *userA.ID, &keycloak.Credential{
		Type:      keycloak.String("password"),
		Value:     keycloak.String("mypassword"),
		Temporary: keycloak.Bool(false),
	})
	if err != nil {
		panic(err)
	}

	// create user
	userB := &keycloak.User{
		Enabled:  keycloak.Bool(true),
		Username: keycloak.String("user_b"),
	}

	res, err = kc.Users.Create(ctx, realm, userB)
	if err != nil {
		panic(err)
	}

	parts = strings.Split(res.Header.Get("Location"), "/")
	userB.ID = &parts[len(parts)-1]

	// set password for user_b
	res, err = kc.Users.ResetPassword(ctx, realm, *userB.ID, &keycloak.Credential{
		Type:      keycloak.String("password"),
		Value:     keycloak.String("mypassword"),
		Temporary: keycloak.Bool(false),
	})
	if err != nil {
		panic(err)
	}

	// create scope
	scopeRead := &keycloak.Scope{
		Name: keycloak.String("scope_read"),
	}

	scopeRead, res, err = kc.Scopes.Create(ctx, realm, *client.ID, scopeRead)
	if err != nil {
		panic(err)
	}

	// create scope
	scopeWrite := &keycloak.Scope{
		Name: keycloak.String("scope_write"),
	}

	scopeWrite, res, err = kc.Scopes.Create(ctx, realm, *client.ID, scopeWrite)
	if err != nil {
		panic(err)
	}

	// create first resource
	resourceProject1 := &keycloak.Resource{
		Name: keycloak.String("Project_1"),
		Uris: []string{"/projects/1"},
		Scopes: []*keycloak.Scope{
			{
				ID:   keycloak.String(*scopeRead.ID),
				Name: keycloak.String("scope_read"),
			},
			{
				ID:   keycloak.String(*scopeWrite.ID),
				Name: keycloak.String("scope_write"),
			}},
	}

	resourceProject1, res, err = kc.Resources.Create(ctx, realm, *client.ID, resourceProject1)
	if err != nil {
		panic(err)
	}

	// create second resource
	resourceProject2 := &keycloak.Resource{
		Name: keycloak.String("Project_2"),
		Uris: []string{"/projects/2"},
		Scopes: []*keycloak.Scope{
			{
				ID:   keycloak.String(*scopeRead.ID),
				Name: keycloak.String("scope_read"),
			},
			{
				ID:   keycloak.String(*scopeWrite.ID),
				Name: keycloak.String("scope_write"),
			}},
	}

	resourceProject2, res, err = kc.Resources.Create(ctx, realm, *client.ID, resourceProject2)
	if err != nil {
		panic(err)
	}

	// create user policy with user_a
	userAPolicy := &keycloak.UserPolicy{
		Policy: keycloak.Policy{
			Type:             keycloak.String("user"),
			Logic:            keycloak.String(keycloak.LogicPositive),
			DecisionStrategy: keycloak.String(keycloak.DecisionStrategyUnanimous),
			Name:             keycloak.String("user_a_policy"),
		},
		Users: []string{*userA.ID},
	}

	userAPolicy, res, err = kc.Policies.CreateUserPolicy(ctx, realm, *client.ID, userAPolicy)
	if err != nil {
		panic(err)
	}

	// create user policy with user_b
	userBPolicy := &keycloak.UserPolicy{
		Policy: keycloak.Policy{
			Type:             keycloak.String("user"),
			Logic:            keycloak.String(keycloak.LogicPositive),
			DecisionStrategy: keycloak.String(keycloak.DecisionStrategyUnanimous),
			Name:             keycloak.String("user_b_policy"),
		},
		Users: []string{*userB.ID},
	}

	userBPolicy, res, err = kc.Policies.CreateUserPolicy(ctx, realm, *client.ID, userBPolicy)
	if err != nil {
		panic(err)
	}

	// create first permission
	permission1 := &keycloak.ScopePermission{
		Permission: keycloak.Permission{
			Type:             keycloak.String("resource"),
			Logic:            keycloak.String(keycloak.LogicPositive),
			DecisionStrategy: keycloak.String(keycloak.DecisionStrategyUnanimous),
			Name:             keycloak.String("permission__project_1__user_a_policy"),
			Resources:        []string{*resourceProject1.ID},
			Policies:         []string{*userAPolicy.ID},
			Scopes:           []string{*scopeRead.ID},
		},
		ResourceType: keycloak.String(""),
	}
	permission1, res, err = kc.Permissions.CreateScopePermission(ctx, realm, *client.ID, permission1)
	if err != nil {
		panic(err)
	}

	permission2 := &keycloak.ScopePermission{
		Permission: keycloak.Permission{
			Type:             keycloak.String("resource"),
			Logic:            keycloak.String(keycloak.LogicPositive),
			DecisionStrategy: keycloak.String(keycloak.DecisionStrategyUnanimous),
			Name:             keycloak.String("permission__project_2__user_b_policy"),
			Resources:        []string{*resourceProject2.ID},
			Policies:         []string{*userBPolicy.ID},
			Scopes:           []string{*scopeRead.ID},
		},
		ResourceType: keycloak.String(""),
	}
	permission2, res, err = kc.Permissions.CreateScopePermission(ctx, realm, *client.ID, permission2)
	if err != nil {
		panic(err)
	}

	// get client secret
	credential, _, err := kc.Clients.GetSecret(ctx, realm, *client.ID)
	if err != nil {
		panic(err)
	}

	// pretend to be user_a
	userAConfig := oauth2.Config{
		ClientID:     clientID,
		ClientSecret: *credential.Value,
		Endpoint: oauth2.Endpoint{
			TokenURL: fmt.Sprintf("http://localhost:8080/realms/%s/protocol/openid-connect/token", realm),
		},
	}

	userAToken, err := userAConfig.PasswordCredentialsToken(ctx, "user_a", "mypassword")
	if err != nil {
		panic(err)
	}

	clientConfig := clientcredentials.Config{
		ClientID:     clientID,
		ClientSecret: *credential.Value,
		TokenURL:     fmt.Sprintf("http://localhost:8080/realms/%s/protocol/openid-connect/token", realm),
		EndpointParams: url.Values{
			"grant_type": {"urn:ietf:params:oauth:grant-type:uma-ticket"},
			"permission": {*resourceProject1.Name + "#scope_read"},
			"audience":   {clientID},
		},
	}

	ctx = context.WithValue(context.Background(), oauth2.HTTPClient, &http.Client{
		Transport: &oauth2.Transport{
			Source: oauth2.StaticTokenSource(userAToken),
		},
	})

	// ask keycloak for permission for reading Project_1
	token, err = clientConfig.Token(ctx)
	if err != nil {
		panic(err)
	}

	// ask keycloak for permission for reading Project_2
	clientConfig.EndpointParams.Set("permission", *resourceProject2.Name+"#scope_read")

	token, err = clientConfig.Token(ctx)
	if err == nil {
		panic("got no error, expected one")
	}
	retrieveError, ok := err.(*oauth2.RetrieveError)
	if !ok {
		panic(fmt.Errorf("got %T error, expected *RetrieveError; error was: %v", err, err))
	}

	fmt.Println(retrieveError.Response.Status)
}
Output:

403 Forbidden

Index

Examples

Constants

View Source
const (
	// AFFIRMATIVE defines that at least one policy must evaluate to a positive decision
	// in order to the overall decision be also positive.
	DecisionStrategyAffirmative = "AFFIRMATIVE"

	// UNANIMOUS defines that all policies must evaluate to a positive decision
	// in order to the overall decision be also positive.
	DecisionStrategyUnanimous = "UNANIMOUS"

	// CONSENSUS defines that the number of positive decisions must be greater than the number of negative decisions.
	// If the number of positive and negative is the same, the final decision will be negative.
	DecisionStrategyConsensus = "CONSENSUS"
)

The decision strategy dictates how the policies associated with a given policy are evaluated and how a final decision is obtained.

https://github.com/keycloak/keycloak/blob/master/core/src/main/java/org/keycloak/representations/idm/authorization/DecisionStrategy.java

View Source
const (
	// Defines that this policy follows a positive logic. In other words, the final decision is the policy outcome.
	LogicPositive = "POSITIVE"

	// Defines that this policy uses a logical negation. In other words, the final decision would be a negative of the policy outcome.
	LogicNegative = "NEGATIVE"
)

The decision strategy dictates how the policies associated with a given policy are evaluated and how a final decision is obtained.

https://github.com/keycloak/keycloak/blob/master/core/src/main/java/org/keycloak/representations/idm/authorization/Logic.java

Variables

This section is empty.

Functions

func Bool

func Bool(v bool) *bool

Bool is a helper routine that allocates a new bool value to store v and returns a pointer to it.

func String

func String(v string) *string

String is a helper routine that allocates a new string value to store v and returns a pointer to it.

Types

type Client

type Client struct {
	ID                                 *string            `json:"id,omitempty"`
	ClientID                           *string            `json:"clientId,omitempty"`
	Name                               *string            `json:"name,omitempty"`
	RootURL                            *string            `json:"rootUrl,omitempty"`
	BaseURL                            *string            `json:"baseUrl,omitempty"`
	SurrogateAuthRequired              *bool              `json:"surrogateAuthRequired,omitempty"`
	Enabled                            *bool              `json:"enabled,omitempty"`
	AlwaysDisplayInConsole             *bool              `json:"alwaysDisplayInConsole,omitempty"`
	ClientAuthenticatorType            *string            `json:"clientAuthenticatorType,omitempty"`
	DefaultRoles                       []string           `json:"defaultRoles,omitempty"`
	RedirectUris                       []string           `json:"redirectUris,omitempty"`
	WebOrigins                         []string           `json:"webOrigins,omitempty"`
	NotBefore                          *int               `json:"notBefore,omitempty"`
	BearerOnly                         *bool              `json:"bearerOnly,omitempty"`
	ConsentRequired                    *bool              `json:"consentRequired,omitempty"`
	StandardFlowEnabled                *bool              `json:"standardFlowEnabled,omitempty"`
	ImplicitFlowEnabled                *bool              `json:"implicitFlowEnabled,omitempty"`
	DirectAccessGrantsEnabled          *bool              `json:"directAccessGrantsEnabled,omitempty"`
	ServiceAccountsEnabled             *bool              `json:"serviceAccountsEnabled,omitempty"`
	AuthorizationServicesEnabled       *bool              `json:"authorizationServicesEnabled,omitempty"`
	PublicClient                       *bool              `json:"publicClient,omitempty"`
	FrontchannelLogout                 *bool              `json:"frontchannelLogout,omitempty"`
	Protocol                           *string            `json:"protocol,omitempty"`
	Attributes                         *map[string]string `json:"attributes,omitempty"`
	AuthenticationFlowBindingOverrides *map[string]string `json:"authenticationFlowBindingOverrides,omitempty"`
	FullScopeAllowed                   *bool              `json:"fullScopeAllowed,omitempty"`
	NodeReRegistrationTimeout          *int               `json:"nodeReRegistrationTimeout,omitempty"`
	DefaultClientScopes                []string           `json:"defaultClientScopes,omitempty"`
	OptionalClientScopes               []string           `json:"optionalClientScopes,omitempty"`
	Access                             *map[string]bool   `json:"access,omitempty"`
}

Client represents a Keycloak client.

https://github.com/keycloak/keycloak/blob/master/core/src/main/java/org/keycloak/representations/idm/ClientRepresentation.java

type ClientRolesService

type ClientRolesService service

ClientRolesService handles communication with the client roles related methods of the Keycloak API.

func (*ClientRolesService) Create

func (s *ClientRolesService) Create(ctx context.Context, realm, id string, role *Role) (*http.Response, error)

Create creates a new client role.

func (*ClientRolesService) DeleteByID

func (s *ClientRolesService) DeleteByID(ctx context.Context, realm, roleID, clientID string) (*http.Response, error)

DeleteByID deletes client role by id.

func (*ClientRolesService) Get

func (s *ClientRolesService) Get(ctx context.Context, realm, id, roleName string) (*Role, *http.Response, error)

Get retrieves a single client role.

func (*ClientRolesService) GetByID

func (s *ClientRolesService) GetByID(ctx context.Context, realm, roleID, clientID string) (*Role, *http.Response, error)

GetByID gets client role by id.

func (*ClientRolesService) GetUsers

func (s *ClientRolesService) GetUsers(ctx context.Context, realm, clientID, role string, opts *Options) ([]*User, *http.Response, error)

GetUsers returns a stream of users that have the specified role name.

func (*ClientRolesService) List

func (s *ClientRolesService) List(ctx context.Context, realm, id string) ([]*Role, *http.Response, error)

List lists all client roles.

type ClientScope

type ClientScope struct {
	ID          *string            `json:"id,omitempty"`
	Name        *string            `json:"name,omitempty"`
	Description *string            `json:"description,omitempty"`
	Protocol    *string            `json:"protocol,omitempty"`
	Attributes  *map[string]string `json:"attributes,omitempty"`
}

ClientScope representation.

https://github.com/keycloak/keycloak/blob/master/core/src/main/java/org/keycloak/representations/idm/ClientScopeRepresentation.java

type ClientScopesService

type ClientScopesService service

ClientScopesService ...

func (*ClientScopesService) Create

func (s *ClientScopesService) Create(ctx context.Context, realm string, clientScope *ClientScope) (*http.Response, error)

Create a new client scope.

func (*ClientScopesService) Delete

func (s *ClientScopesService) Delete(ctx context.Context, realm, clientScopeID string) (*http.Response, error)

Delete client scope.

func (*ClientScopesService) Get

func (s *ClientScopesService) Get(ctx context.Context, realm, clientScopeID string) (*ClientScope, *http.Response, error)

Get client scope.

func (*ClientScopesService) List

List all client scopes in realm.

type ClientsService

type ClientsService service

ClientsService handles communication with the client related methods of the Keycloak API.

func (*ClientsService) Create

func (s *ClientsService) Create(ctx context.Context, realm string, client *Client) (*http.Response, error)

Create a new client.

Example
kc, err := keycloak.NewKeycloak(nil, "http://localhost:8080/")
if err != nil {
	panic(err)
}

client := &keycloak.Client{
	Enabled:  keycloak.Bool(true),
	ClientID: keycloak.String("myclient"),
}

ctx := context.Background()
res, err := kc.Clients.Create(ctx, "myrealm", client)
if err != nil {
	panic(err)
}

fmt.Println(res)
Output:

func (*ClientsService) CreateSecret

func (s *ClientsService) CreateSecret(ctx context.Context, realm, id string) (*Credential, *http.Response, error)

CreateSecret generates a new secret for the client

func (*ClientsService) Delete

func (s *ClientsService) Delete()

Delete ...

func (*ClientsService) Get

func (s *ClientsService) Get(ctx context.Context, realm, id string) (*Client, *http.Response, error)

Get client.

func (*ClientsService) GetSecret

func (s *ClientsService) GetSecret(ctx context.Context, realm, id string) (*Credential, *http.Response, error)

GetSecret gets client secret.

func (*ClientsService) List

func (s *ClientsService) List(ctx context.Context, realm string) ([]*Client, *http.Response, error)

List all clients in realm.

func (*ClientsService) Update

func (s *ClientsService) Update(ctx context.Context, realm string, client *Client) (*http.Response, error)

Update a new client.

type Configuration

type Configuration struct {
	Issuer                                     *string  `json:"issuer,omitempty"`
	AuthorizationEndpoint                      *string  `json:"authorization_endpoint,omitempty"`
	TokenEndpoint                              *string  `json:"token_endpoint,omitempty"`
	IntrospectionEndpoint                      *string  `json:"introspection_endpoint,omitempty"`
	EndSessionEndpoint                         *string  `json:"end_session_endpoint,omitempty"`
	JwksURI                                    *string  `json:"jwks_uri,omitempty"`
	GrantTypesSupported                        []string `json:"grant_types_supported,omitempty"`
	ResponseTypesSupported                     []string `json:"response_types_supported,omitempty"`
	ResponseModesSupported                     []string `json:"response_modes_supported,omitempty"`
	RegistrationEndpoint                       *string  `json:"registration_endpoint,omitempty"`
	TokenEndpointAuthMethodsSupported          []string `json:"token_endpoint_auth_methods_supported,omitempty"`
	TokenEndpointAuthSigningAlgValuesSupported []string `json:"token_endpoint_auth_signing_alg_values_supported,omitempty"`
	ScopesSupported                            []string `json:"scopes_supported,omitempty"`
	ResourceRegistrationEndpoint               *string  `json:"resource_registration_endpoint,omitempty"`
	PermissionEndpoint                         *string  `json:"permission_endpoint,omitempty"`
	PolicyEndpoint                             *string  `json:"policy_endpoint,omitempty"`
}

Configuration represents a UMA configuration.

type Credential

type Credential struct {
	Type      *string `json:"type,omitempty"`
	Value     *string `json:"value,omitempty"`
	Temporary *bool   `json:"temporary,omitempty"`
}

Credential representation.

https://github.com/keycloak/keycloak/blob/master/core/src/main/java/org/keycloak/representations/idm/CredentialRepresentation.java

type ExecuteActionsEmailOptions

type ExecuteActionsEmailOptions struct {
	ClientID    string `url:"client_id,omitempty"`
	Lifespan    int    `url:"lifespan,omitempty"`
	RedirectUri string `url:"redirect_uri,omitempty"`
}

ExecuteActionsEmailOptions ...

type Group

type Group struct {
	ID          *string              `json:"id,omitempty"`
	Name        *string              `json:"name,omitempty"`
	Path        *string              `json:"path,omitempty"`
	Attributes  *map[string][]string `json:"attributes,omitempty"`
	RealmRoles  []string             `json:"realmRoles,omitempty"`
	ClientRoles *map[string][]string `json:"clientRoles,omitempty"`
	SubGroups   []*Group             `json:"subGroups,omitempty"`
	Access      *map[string]bool     `json:"access,omitempty"`
}

Group ...

type GroupDefinition

type GroupDefinition struct {
	ID             *string `json:"id,omitempty"`
	Path           *string `json:"path,omitempty"`
	ExtendChildren *bool   `json:"extendChildren,omitempty"`
}

GroupDefinition represents a Keycloak groupDefinition.

https://github.com/keycloak/keycloak/blob/master/core/src/main/java/org/keycloak/representations/idm/authorization/GroupPolicyRepresentation.java

type GroupPolicy

type GroupPolicy struct {
	Policy
	GroupsClaim *string            `json:"groupsClaim,omitempty"`
	Groups      []*GroupDefinition `json:"groups,omitempty"`
}

GroupPolicy represents a Keycloak group policy.

https://github.com/keycloak/keycloak/blob/master/core/src/main/java/org/keycloak/representations/idm/authorization/GroupPolicyRepresentation.java

type GroupsService

type GroupsService service

GroupsService ...

func (*GroupsService) AddRealmRoles

func (s *GroupsService) AddRealmRoles(ctx context.Context, realm, groupID string, roles []*Role) (*http.Response, error)

func (*GroupsService) Create

func (s *GroupsService) Create(ctx context.Context, realm string, group *Group) (*http.Response, error)

Create a new group.

Example
kc, err := keycloak.NewKeycloak(nil, "http://localhost:8080/")
if err != nil {
	panic(err)
}

group := &keycloak.Group{
	Name: keycloak.String("mygroup"),
}

ctx := context.Background()
res, err := kc.Groups.Create(ctx, "myrealm", group)
if err != nil {
	panic(err)
}

fmt.Println(res)
Output:

func (*GroupsService) Delete

func (s *GroupsService) Delete(ctx context.Context, realm, groupID string) (*http.Response, error)

Delete group.

func (*GroupsService) Get

func (s *GroupsService) Get(ctx context.Context, realm, groupID string) (*Group, *http.Response, error)

Get group.

func (*GroupsService) List

func (s *GroupsService) List(ctx context.Context, realm string) ([]*Group, *http.Response, error)

List groups.

func (*GroupsService) ListGroupMembers

func (s *GroupsService) ListGroupMembers(ctx context.Context, realm string, userId string) ([]*User, *http.Response, error)

List group members.

func (*GroupsService) RemoveRealmRoles

func (s *GroupsService) RemoveRealmRoles(ctx context.Context, realm, groupID string, roles []*Role) (*http.Response, error)

type Keycloak

type Keycloak struct {
	BaseURL *url.URL

	Clients      *ClientsService
	ClientRoles  *ClientRolesService
	ClientScopes *ClientScopesService
	Groups       *GroupsService
	Permissions  *PermissionsService
	Policies     *PoliciesService
	Realms       *RealmsService
	RealmRoles   *RealmRolesService
	Resources    *ResourcesService
	Scopes       *ScopesService
	Users        *UsersService
	// contains filtered or unexported fields
}

Keycloak ...

func NewKeycloak

func NewKeycloak(httpClient *http.Client, baseURL string) (*Keycloak, error)

NewKeycloak ...

Example (Admin)
// create a new oauth2 configuration
config := oauth2.Config{
	ClientID: "admin-cli",
	Endpoint: oauth2.Endpoint{
		TokenURL: "http://localhost:8080/realms/master/protocol/openid-connect/token",
	},
}

ctx := context.Background()

// this should be your KEYCLOAK_USER and your KEYCLOAK_PASSWORD
token, err := config.PasswordCredentialsToken(ctx, "admin", "admin")
if err != nil {
	panic(err)
}

// create a new http client
httpClient := config.Client(ctx, token)

// use the http client to create a Keycloak instance
kc, err := keycloak.NewKeycloak(httpClient, "http://localhost:8080/")
if err != nil {
	panic(err)
}

// then use this instance to make requests to the API
fmt.Println(kc)
Output:

Example (User)
// create a new oauth2 configuration
config := oauth2.Config{
	ClientID:     "40349713-a521-48b2-9197-216adfce5f78",
	ClientSecret: "ddafbeba-1402-4969-bbbb-475d657fa9d5",
	Endpoint: oauth2.Endpoint{
		TokenURL: fmt.Sprintf("http://localhost:8080/realms/%s/protocol/openid-connect/token", "myrealm"),
	},
}

ctx := context.Background()

// this should be your username and your password
token, err := config.PasswordCredentialsToken(ctx, "user", "user_password")
if err != nil {
	panic(err)
}

// create a new http client
httpClient := config.Client(ctx, token)

// use the http client to create a Keycloak instance
kc, err := keycloak.NewKeycloak(httpClient, "http://localhost:8080/")
if err != nil {
	panic(err)
}

// then use this instance to make requests to the API
fmt.Println(kc)
Output:

func (*Keycloak) Do

func (k *Keycloak) Do(ctx context.Context, req *http.Request, v interface{}) (*http.Response, error)

Do ...

func (*Keycloak) NewRequest

func (k *Keycloak) NewRequest(method string, url string, body interface{}) (*http.Request, error)

NewRequest ...

type Options

type Options struct {
	First int    `url:"first,omitempty"`
	Max   string `url:"max,omitempty"`
}

Options ...

type Permission

type Permission struct {
	ID               *string  `json:"id,omitempty"`
	Name             *string  `json:"name,omitempty"`
	Description      *string  `json:"description,omitempty"`
	Type             *string  `json:"type,omitempty"`
	Policies         []string `json:"policies,omitempty"`
	Resources        []string `json:"resources,omitempty"`
	Scopes           []string `json:"scopes,omitempty"`
	Logic            *string  `json:"logic,omitempty"`
	DecisionStrategy *string  `json:"decisionStrategy,omitempty"`
	Owner            *string  `json:"owner,omitempty"`
}

Permission represents a Keycloak abstract permission.

https://github.com/keycloak/keycloak/blob/master/core/src/main/java/org/keycloak/representations/idm/authorization/AbstractPolicyRepresentation.java

type PermissionsService

type PermissionsService service

PermissionsService handles communication with the permissions related methods of the Keycloak API.

func (*PermissionsService) CreateResourcePermission

func (s *PermissionsService) CreateResourcePermission(ctx context.Context, realm, clientID string, permission *ResourcePermission) (*ResourcePermission, *http.Response, error)

CreateResourcePermission creates a new resource based permission.

func (*PermissionsService) CreateScopePermission

func (s *PermissionsService) CreateScopePermission(ctx context.Context, realm, clientID string, permission *ScopePermission) (*ScopePermission, *http.Response, error)

CreateScopePermission creates a new scope based permission.

func (*PermissionsService) GetResourcePermission

func (s *PermissionsService) GetResourcePermission(ctx context.Context, realm, clientID, permissionID string) (*ResourcePermission, *http.Response, error)

GetResourcePermission gets resource based permission by id.

func (*PermissionsService) GetScopePermission

func (s *PermissionsService) GetScopePermission(ctx context.Context, realm, clientID, permissionID string) (*ScopePermission, *http.Response, error)

GetScopePermission gets scope based permission by id.

func (*PermissionsService) List

func (s *PermissionsService) List(ctx context.Context, realm, clientID string) ([]*Permission, *http.Response, error)

List lists all permissions.

type PoliciesService

type PoliciesService service

PoliciesService handles communication with the policies related methods of the Keycloak API.

func (*PoliciesService) CreateGroupPolicy

func (s *PoliciesService) CreateGroupPolicy(ctx context.Context, realm, clientID string, policy *GroupPolicy) (*GroupPolicy, *http.Response, error)

CreateGroupPolicy creates a new group policy.

func (*PoliciesService) CreateRolePolicy

func (s *PoliciesService) CreateRolePolicy(ctx context.Context, realm, clientID string, policy *RolePolicy) (*RolePolicy, *http.Response, error)

CreateRolePolicy creates a new role policy.

func (*PoliciesService) CreateUserPolicy

func (s *PoliciesService) CreateUserPolicy(ctx context.Context, realm, clientID string, policy *UserPolicy) (*UserPolicy, *http.Response, error)

CreateUserPolicy creates a new user policy.

Example
kc, err := keycloak.NewKeycloak(nil, "http://localhost:8080/")
if err != nil {
	panic(err)
}

policy := &keycloak.UserPolicy{
	Policy: keycloak.Policy{
		Type:             keycloak.String("user"),
		Logic:            keycloak.String(keycloak.LogicPositive),
		DecisionStrategy: keycloak.String(keycloak.DecisionStrategyUnanimous),
		Name:             keycloak.String("policy"),
	},
	Users: []string{"89400c55-15fd-4e5d-a7c9-403f431d97f3"},
}

ctx := context.Background()

clientID := "40349713-a521-48b2-9197-216adfce5f78"
policy, res, err := kc.Policies.CreateUserPolicy(ctx, "myrealm", clientID, policy)
if err != nil {
	panic(err)
}

fmt.Println(res)
Output:

func (*PoliciesService) List

func (s *PoliciesService) List(ctx context.Context, realm, clientID string) ([]*Policy, *http.Response, error)

List lists all policies.

type Policy

type Policy struct {
	ID               *string  `json:"id,omitempty"`
	Name             *string  `json:"name,omitempty"`
	Description      *string  `json:"description,omitempty"`
	Type             *string  `json:"type,omitempty"`
	Policies         []string `json:"policies,omitempty"`
	Resources        []string `json:"resources,omitempty"`
	Scopes           []string `json:"scopes,omitempty"`
	Logic            *string  `json:"logic,omitempty"`
	DecisionStrategy *string  `json:"decisionStrategy,omitempty"`
	Owner            *string  `json:"owner,omitempty"`
}

Policy represents a Keycloak abstract policy.

https://github.com/keycloak/keycloak/blob/master/core/src/main/java/org/keycloak/representations/idm/authorization/AbstractPolicyRepresentation.java

type Realm

type Realm struct {
	ID                                                        *string                   `json:"id,omitempty"`
	Realm                                                     *string                   `json:"realm,omitempty"`
	DisplayName                                               *string                   `json:"displayName,omitempty"`
	DisplayNameHTML                                           *string                   `json:"displayNameHtml,omitempty"`
	NotBefore                                                 *int                      `json:"notBefore,omitempty"`
	RevokeRefreshToken                                        *bool                     `json:"revokeRefreshToken,omitempty"`
	RefreshTokenMaxReuse                                      *int                      `json:"refreshTokenMaxReuse,omitempty"`
	AccessTokenLifespan                                       *int                      `json:"accessTokenLifespan,omitempty"`
	AccessTokenLifespanForImplicitFlow                        *int                      `json:"accessTokenLifespanForImplicitFlow,omitempty"`
	SsoSessionIdleTimeout                                     *int                      `json:"ssoSessionIdleTimeout,omitempty"`
	SsoSessionMaxLifespan                                     *int                      `json:"ssoSessionMaxLifespan,omitempty"`
	SsoSessionIdleTimeoutRememberMe                           *int                      `json:"ssoSessionIdleTimeoutRememberMe,omitempty"`
	SsoSessionMaxLifespanRememberMe                           *int                      `json:"ssoSessionMaxLifespanRememberMe,omitempty"`
	OfflineSessionIdleTimeout                                 *int                      `json:"offlineSessionIdleTimeout,omitempty"`
	OfflineSessionMaxLifespanEnabled                          *bool                     `json:"offlineSessionMaxLifespanEnabled,omitempty"`
	OfflineSessionMaxLifespan                                 *int                      `json:"offlineSessionMaxLifespan,omitempty"`
	ClientSessionIdleTimeout                                  *int                      `json:"clientSessionIdleTimeout,omitempty"`
	ClientSessionMaxLifespan                                  *int                      `json:"clientSessionMaxLifespan,omitempty"`
	ClientOfflineSessionIdleTimeout                           *int                      `json:"clientOfflineSessionIdleTimeout,omitempty"`
	ClientOfflineSessionMaxLifespan                           *int                      `json:"clientOfflineSessionMaxLifespan,omitempty"`
	AccessCodeLifespan                                        *int                      `json:"accessCodeLifespan,omitempty"`
	AccessCodeLifespanUserAction                              *int                      `json:"accessCodeLifespanUserAction,omitempty"`
	AccessCodeLifespanLogin                                   *int                      `json:"accessCodeLifespanLogin,omitempty"`
	ActionTokenGeneratedByAdminLifespan                       *int                      `json:"actionTokenGeneratedByAdminLifespan,omitempty"`
	ActionTokenGeneratedByUserLifespan                        *int                      `json:"actionTokenGeneratedByUserLifespan,omitempty"`
	Enabled                                                   *bool                     `json:"enabled,omitempty"`
	SslRequired                                               *string                   `json:"sslRequired,omitempty"`
	RegistrationAllowed                                       *bool                     `json:"registrationAllowed,omitempty"`
	RegistrationEmailAsUsername                               *bool                     `json:"registrationEmailAsUsername,omitempty"`
	RememberMe                                                *bool                     `json:"rememberMe,omitempty"`
	VerifyEmail                                               *bool                     `json:"verifyEmail,omitempty"`
	LoginWithEmailAllowed                                     *bool                     `json:"loginWithEmailAllowed,omitempty"`
	DuplicateEmailsAllowed                                    *bool                     `json:"duplicateEmailsAllowed,omitempty"`
	ResetPasswordAllowed                                      *bool                     `json:"resetPasswordAllowed,omitempty"`
	EditUsernameAllowed                                       *bool                     `json:"editUsernameAllowed,omitempty"`
	BruteForceProtected                                       *bool                     `json:"bruteForceProtected,omitempty"`
	PermanentLockout                                          *bool                     `json:"permanentLockout,omitempty"`
	MaxFailureWaitSeconds                                     *int                      `json:"maxFailureWaitSeconds,omitempty"`
	MinimumQuickLoginWaitSeconds                              *int                      `json:"minimumQuickLoginWaitSeconds,omitempty"`
	WaitIncrementSeconds                                      *int                      `json:"waitIncrementSeconds,omitempty"`
	QuickLoginCheckMilliSeconds                               *int                      `json:"quickLoginCheckMilliSeconds,omitempty"`
	MaxDeltaTimeSeconds                                       *int                      `json:"maxDeltaTimeSeconds,omitempty"`
	FailureFactor                                             *int                      `json:"failureFactor,omitempty"`
	DefaultRoles                                              []string                  `json:"defaultRoles,omitempty"`
	RequiredCredentials                                       []string                  `json:"requiredCredentials,omitempty"`
	OtpPolicyType                                             *string                   `json:"otpPolicyType,omitempty"`
	OtpPolicyAlgorithm                                        *string                   `json:"otpPolicyAlgorithm,omitempty"`
	OtpPolicyInitialCounter                                   *int                      `json:"otpPolicyInitialCounter,omitempty"`
	OtpPolicyDigits                                           *int                      `json:"otpPolicyDigits,omitempty"`
	OtpPolicyLookAheadWindow                                  *int                      `json:"otpPolicyLookAheadWindow,omitempty"`
	OtpPolicyPeriod                                           *int                      `json:"otpPolicyPeriod,omitempty"`
	OtpSupportedApplications                                  []string                  `json:"otpSupportedApplications,omitempty"`
	WebAuthnPolicyRpEntityName                                *string                   `json:"webAuthnPolicyRpEntityName,omitempty"`
	WebAuthnPolicySignatureAlgorithms                         []string                  `json:"webAuthnPolicySignatureAlgorithms,omitempty"`
	WebAuthnPolicyRpID                                        *string                   `json:"webAuthnPolicyRpId,omitempty"`
	WebAuthnPolicyAttestationConveyancePreference             *string                   `json:"webAuthnPolicyAttestationConveyancePreference,omitempty"`
	WebAuthnPolicyAuthenticatorAttachment                     *string                   `json:"webAuthnPolicyAuthenticatorAttachment,omitempty"`
	WebAuthnPolicyRequireResidentKey                          *string                   `json:"webAuthnPolicyRequireResidentKey,omitempty"`
	WebAuthnPolicyUserVerificationRequirement                 *string                   `json:"webAuthnPolicyUserVerificationRequirement,omitempty"`
	WebAuthnPolicyCreateTimeout                               *int                      `json:"webAuthnPolicyCreateTimeout,omitempty"`
	WebAuthnPolicyAvoidSameAuthenticatorRegister              *bool                     `json:"webAuthnPolicyAvoidSameAuthenticatorRegister,omitempty"`
	WebAuthnPolicyAcceptableAaguids                           []string                  `json:"webAuthnPolicyAcceptableAaguids,omitempty"`
	WebAuthnPolicyPasswordlessRpEntityName                    *string                   `json:"webAuthnPolicyPasswordlessRpEntityName,omitempty"`
	WebAuthnPolicyPasswordlessSignatureAlgorithms             []string                  `json:"webAuthnPolicyPasswordlessSignatureAlgorithms,omitempty"`
	WebAuthnPolicyPasswordlessRpID                            *string                   `json:"webAuthnPolicyPasswordlessRpId,omitempty"`
	WebAuthnPolicyPasswordlessAttestationConveyancePreference *string                   `json:"webAuthnPolicyPasswordlessAttestationConveyancePreference,omitempty"`
	WebAuthnPolicyPasswordlessAuthenticatorAttachment         *string                   `json:"webAuthnPolicyPasswordlessAuthenticatorAttachment,omitempty"`
	WebAuthnPolicyPasswordlessRequireResidentKey              *string                   `json:"webAuthnPolicyPasswordlessRequireResidentKey,omitempty"`
	WebAuthnPolicyPasswordlessUserVerificationRequirement     *string                   `json:"webAuthnPolicyPasswordlessUserVerificationRequirement,omitempty"`
	WebAuthnPolicyPasswordlessCreateTimeout                   *int                      `json:"webAuthnPolicyPasswordlessCreateTimeout,omitempty"`
	WebAuthnPolicyPasswordlessAvoidSameAuthenticatorRegister  *bool                     `json:"webAuthnPolicyPasswordlessAvoidSameAuthenticatorRegister,omitempty"`
	WebAuthnPolicyPasswordlessAcceptableAaguids               []string                  `json:"webAuthnPolicyPasswordlessAcceptableAaguids,omitempty"`
	BrowserSecurityHeaders                                    *map[string]string        `json:"browserSecurityHeaders,omitempty"`
	SMTPServer                                                *map[string]string        `json:"smtpServer,omitempty"`
	EventsEnabled                                             *bool                     `json:"eventsEnabled,omitempty"`
	EventsListeners                                           []string                  `json:"eventsListeners,omitempty"`
	EnabledEventTypes                                         []string                  `json:"enabledEventTypes,omitempty"`
	AdminEventsEnabled                                        *bool                     `json:"adminEventsEnabled,omitempty"`
	AdminEventsDetailsEnabled                                 *bool                     `json:"adminEventsDetailsEnabled,omitempty"`
	IdentityProviders                                         []*IdentityProvider       `json:"identityProviders,omitempty"`
	IdentityProviderMappers                                   []*IdentityProviderMapper `json:"identityProviderMappers,omitempty"`
	InternationalizationEnabled                               *bool                     `json:"internationalizationEnabled,omitempty"`
	SupportedLocales                                          []string                  `json:"supportedLocales,omitempty"`
	BrowserFlow                                               *string                   `json:"browserFlow,omitempty"`
	RegistrationFlow                                          *string                   `json:"registrationFlow,omitempty"`
	DirectGrantFlow                                           *string                   `json:"directGrantFlow,omitempty"`
	ResetCredentialsFlow                                      *string                   `json:"resetCredentialsFlow,omitempty"`
	ClientAuthenticationFlow                                  *string                   `json:"clientAuthenticationFlow,omitempty"`
	DockerAuthenticationFlow                                  *string                   `json:"dockerAuthenticationFlow,omitempty"`
	Attributes                                                *map[string]string        `json:"attributes,omitempty"`
	UserManagedAccessAllowed                                  *bool                     `json:"userManagedAccessAllowed,omitempty"`
}

Realm representation.

https://github.com/keycloak/keycloak/blob/master/core/src/main/java/org/keycloak/representations/idm/RealmRepresentation.java

type RealmRolesService

type RealmRolesService service

RealmRolesService ...

func (*RealmRolesService) Create

func (s *RealmRolesService) Create(ctx context.Context, realm string, role *Role) (*http.Response, error)

Create a new role.

Example
kc, err := keycloak.NewKeycloak(nil, "http://localhost:8080/")
if err != nil {
	panic(err)
}

role := &keycloak.Role{
	Name:        keycloak.String("my name"),
	Description: keycloak.String("my description"),
}

ctx := context.Background()
res, err := kc.RealmRoles.Create(ctx, "myrealm", role)
if err != nil {
	panic(err)
}

fmt.Println(res)
Output:

func (*RealmRolesService) GetByID

func (s *RealmRolesService) GetByID(ctx context.Context, realm, roleID string) (*Role, *http.Response, error)

GetByID gets role by id.

func (*RealmRolesService) GetByName

func (s *RealmRolesService) GetByName(ctx context.Context, realm, name string) (*Role, *http.Response, error)

GetByName gets role by name.

func (*RealmRolesService) List

func (s *RealmRolesService) List(ctx context.Context, realm string, opts *RolesListOptions) ([]*Role, *http.Response, error)

List roles.

type RealmsService

type RealmsService service

RealmsService ...

func (*RealmsService) Create

func (s *RealmsService) Create(ctx context.Context, realm *Realm) (*http.Response, error)

Create a new realm.

Example
kc, err := keycloak.NewKeycloak(nil, "http://localhost:8080/")
if err != nil {
	panic(err)
}

realm := &keycloak.Realm{
	Enabled: keycloak.Bool(true),
	ID:      keycloak.String("myrealm"),
	Realm:   keycloak.String("myrealm"),
}

ctx := context.Background()

res, err := kc.Realms.Create(ctx, realm)
if err != nil {
	panic(err)
}

fmt.Println(res)
Output:

func (*RealmsService) Delete

func (s *RealmsService) Delete(ctx context.Context, name string) (*http.Response, error)

Delete realm.

func (*RealmsService) Get

func (s *RealmsService) Get(ctx context.Context, name string) (*Realm, *http.Response, error)

Get realm.

func (*RealmsService) GetConfig

func (s *RealmsService) GetConfig(ctx context.Context, name string) (*Configuration, *http.Response, error)

GetConfig gets realm configuration.

func (*RealmsService) List

func (s *RealmsService) List(ctx context.Context) ([]*Realm, *http.Response, error)

List all realms.

type Resource

type Resource struct {
	ID                 *string              `json:"_id,omitempty"`
	Scopes             []*Scope             `json:"scopes,omitempty"`
	Attributes         *map[string][]string `json:"attributes,omitempty"`
	Uris               []string             `json:"uris,omitempty"`
	Name               *string              `json:"name,omitempty"`
	OwnerManagedAccess *bool                `json:"ownerManagedAccess,omitempty"`
	DisplayName        *string              `json:"displayName,omitempty"`
	Owner              *ResourceOwner       `json:"owner,omitempty"`
}

Resource represents a Keycloak resource.

https://github.com/keycloak/keycloak/blob/master/core/src/main/java/org/keycloak/representations/idm/authorization/ResourceRepresentation.java

type ResourceOwner

type ResourceOwner struct {
	ID   *string `json:"id,omitempty"`
	Name *string `json:"name,omitempty"`
}

ResourceOwner represents a Keycloak resource owner.

https://github.com/keycloak/keycloak/blob/master/core/src/main/java/org/keycloak/representations/idm/authorization/ResourceOwnerRepresentation.java

type ResourcePermission

type ResourcePermission struct {
	Permission
	ResourceType *string `json:"resourceType,omitempty"`
}

ResourcePermission represents a Keycloak resource permission.

https://github.com/keycloak/keycloak/blob/master/core/src/main/java/org/keycloak/representations/idm/authorization/ResourcePermissionRepresentation.java

type ResourcesService

type ResourcesService service

ResourcesService handles communication with the resources related methods of the Keycloak API.

func (*ResourcesService) Create

func (s *ResourcesService) Create(ctx context.Context, realm, clientID string, resource *Resource) (*Resource, *http.Response, error)

Create creates a new resource.

Example
kc, err := keycloak.NewKeycloak(nil, "http://localhost:8080/")
if err != nil {
	panic(err)
}

resource := &keycloak.Resource{
	Name:        keycloak.String("resource"),
	DisplayName: keycloak.String("resource"),
}

ctx := context.Background()

clientID := "40349713-a521-48b2-9197-216adfce5f78"
resource, res, err := kc.Resources.Create(ctx, "myrealm", clientID, resource)
if err != nil {
	panic(err)
}

fmt.Println(res)
Output:

func (*ResourcesService) Delete

func (s *ResourcesService) Delete(ctx context.Context, realm, clientID, resourceID string) (*http.Response, error)

Delete deletes a single resource.

func (*ResourcesService) Get

func (s *ResourcesService) Get(ctx context.Context, realm, clientID, resourceID string) (*Resource, *http.Response, error)

Get gets a single resource.

func (*ResourcesService) List

func (s *ResourcesService) List(ctx context.Context, realm, clientID string) ([]*Resource, *http.Response, error)

List lists all resources.

type Role

type Role struct {
	ID          *string              `json:"id,omitempty"`
	Name        *string              `json:"name,omitempty"`
	Description *string              `json:"description,omitempty"`
	Composite   *bool                `json:"composite,omitempty"`
	ClientRole  *bool                `json:"clientRole,omitempty"`
	ContainerID *string              `json:"containerId,omitempty"`
	Attributes  *map[string][]string `json:"attributes,omitempty"`
}

Role representation

type RoleDefinition

type RoleDefinition struct {
	ID       *string `json:"id,omitempty"`
	Required *bool   `json:"required,omitempty"`
}

RoleDefinition represents a Keycloak role definition.

https://github.com/keycloak/keycloak/blob/master/core/src/main/java/org/keycloak/representations/idm/authorization/RolePolicyRepresentation.java

type RolePolicy

type RolePolicy struct {
	Policy
	Roles []*RoleDefinition `json:"roles,omitempty"`
}

RolePolicy represents a Keycloak role policy.

https://github.com/keycloak/keycloak/blob/master/core/src/main/java/org/keycloak/representations/idm/authorization/RolePolicyRepresentation.java

type RolesListOptions

type RolesListOptions struct {
	BriefRepresentation bool `url:"briefRepresentation,omitempty"`
	Search              bool `url:"search,omitempty"`
	Options
}

RolesListOptions ...

type Scope

type Scope struct {
	ID          *string `json:"id,omitempty"`
	Name        *string `json:"name,omitempty"`
	IconURI     *string `json:"iconUri,omitempty"`
	DisplayName *string `json:"displayName,omitempty"`
}

Scope represents a Keycloak scope.

https://github.com/keycloak/keycloak/blob/master/core/src/main/java/org/keycloak/representations/idm/authorization/ScopeRepresentation.java

type ScopePermission

type ScopePermission struct {
	Permission
	ResourceType *string `json:"resourceType,omitempty"`
}

ScopePermission represents a Keycloak scope permission.

https://github.com/keycloak/keycloak/blob/master/core/src/main/java/org/keycloak/representations/idm/authorization/ScopePermissionRepresentation.java

type ScopesService

type ScopesService service

ScopesService handles communication with the scopes related methods of the Keycloak API.

func (*ScopesService) Create

func (s *ScopesService) Create(ctx context.Context, realm, clientID string, scope *Scope) (*Scope, *http.Response, error)

Create creates a new scope.

Example
kc, err := keycloak.NewKeycloak(nil, "http://localhost:8080/")
if err != nil {
	panic(err)
}

scope := &keycloak.Scope{
	Name: keycloak.String("scope_read"),
}

ctx := context.Background()

clientID := "40349713-a521-48b2-9197-216adfce5f78"
scope, res, err := kc.Scopes.Create(ctx, "myrealm", clientID, scope)
if err != nil {
	panic(err)
}

fmt.Println(res)
Output:

func (*ScopesService) Delete

func (s *ScopesService) Delete(ctx context.Context, realm, clientID, scopeID string) (*http.Response, error)

Delete deletes a single scope.

func (*ScopesService) Get

func (s *ScopesService) Get(ctx context.Context, realm, clientID, scopeID string) (*Scope, *http.Response, error)

Get gets a single scope.

func (*ScopesService) List

func (s *ScopesService) List(ctx context.Context, realm, clientID string) ([]*Scope, *http.Response, error)

List lists all resources.

func (*ScopesService) Update

func (s *ScopesService) Update(ctx context.Context, realm, clientID string, scope *Scope) (*http.Response, error)

Update creates a new scope.

type User

type User struct {
	ID                         *string              `json:"id,omitempty"`
	CreatedTimestamp           *int64               `json:"createdTimestamp,omitempty"`
	Username                   *string              `json:"username,omitempty"`
	Enabled                    *bool                `json:"enabled,omitempty"`
	Totp                       *bool                `json:"totp,omitempty"`
	EmailVerified              *bool                `json:"emailVerified,omitempty"`
	FirstName                  *string              `json:"firstName,omitempty"`
	LastName                   *string              `json:"lastName,omitempty"`
	Email                      *string              `json:"email,omitempty"`
	DisableableCredentialTypes []string             `json:"disableableCredentialTypes,omitempty"`
	RequiredActions            []string             `json:"requiredActions,omitempty"`
	NotBefore                  *int                 `json:"notBefore,omitempty"`
	Access                     *map[string]bool     `json:"access,omitempty"`
	Attributes                 *map[string][]string `json:"attributes,omitempty"`
}

User representation.

https://github.com/keycloak/keycloak/blob/master/core/src/main/java/org/keycloak/representations/idm/UserRepresentation.java

type UserPolicy

type UserPolicy struct {
	Policy
	Users []string `json:"users,omitempty"`
}

UserPolicy represents a Keycloak user policy.

https://github.com/keycloak/keycloak/blob/master/core/src/main/java/org/keycloak/representations/idm/authorization/UserPolicyRepresentation.java

type UsersService

type UsersService service

UsersService ...

func (*UsersService) AddClientRoles

func (s *UsersService) AddClientRoles(ctx context.Context, realm, userID, clientID string, roles []*Role) (*http.Response, error)

AddClientRoles adds client roles to user.

func (*UsersService) AddRealmRoles

func (s *UsersService) AddRealmRoles(ctx context.Context, realm, userID string, roles []*Role) (*http.Response, error)

AddRealmRoles adds realm roles to user.

func (*UsersService) Create

func (s *UsersService) Create(ctx context.Context, realm string, user *User) (*http.Response, error)

Create a new user.

Example
kc, err := keycloak.NewKeycloak(nil, "http://localhost:8080/")
if err != nil {
	panic(err)
}

user := &keycloak.User{
	Enabled:   keycloak.Bool(true),
	Username:  keycloak.String("username"),
	Email:     keycloak.String("user@email.com"),
	FirstName: keycloak.String("first"),
	LastName:  keycloak.String("last"),
}

ctx := context.Background()
res, err := kc.Users.Create(ctx, "myrealm", user)
if err != nil {
	panic(err)
}

fmt.Println(res)
Output:

func (*UsersService) Delete

func (s *UsersService) Delete(ctx context.Context, realm, userID string) (*http.Response, error)

Delete user.

func (*UsersService) ExecuteActionsEmail

func (s *UsersService) ExecuteActionsEmail(ctx context.Context, realm, userID string, opts *ExecuteActionsEmailOptions, actions []string) (*http.Response, error)

ExecuteActionsEmail sends an update account email to the user. An email contains a link the user can click to perform a set of required actions.

func (*UsersService) GetByID

func (s *UsersService) GetByID(ctx context.Context, realm, id string) (*User, *http.Response, error)

GetByID get a single user by ID.

func (*UsersService) GetByUsername

func (s *UsersService) GetByUsername(ctx context.Context, realm, username string) ([]*User, *http.Response, error)

GetByUsername get a single user by username.

func (*UsersService) JoinGroup

func (s *UsersService) JoinGroup(ctx context.Context, realm, userID, groupID string) (*http.Response, error)

JoinGroup adds user to a group.

func (*UsersService) LeaveGroup

func (s *UsersService) LeaveGroup(ctx context.Context, realm, userID, groupID string) (*http.Response, error)

LeaveGroup removes a user from a group.

func (*UsersService) List

func (s *UsersService) List(ctx context.Context, realm string) ([]*User, *http.Response, error)

List users.

func (*UsersService) ListRealmRoles

func (s *UsersService) ListRealmRoles(ctx context.Context, realm, userID string) ([]*Role, *http.Response, error)

ListRealmRoles returns a list of realm roles assigned to user.

func (*UsersService) ListUserGroups

func (s *UsersService) ListUserGroups(ctx context.Context, realm string, id string) ([]*Group, *http.Response, error)

List user groups.

func (*UsersService) RemoveClientRoles

func (s *UsersService) RemoveClientRoles(ctx context.Context, realm, userID, clientID string, roles []*Role) (*http.Response, error)

RemoveClientRoles removes assigned client roles from user.

func (*UsersService) RemoveRealmRoles

func (s *UsersService) RemoveRealmRoles(ctx context.Context, realm, userID string, roles []*Role) (*http.Response, error)

RemoveRealmRoles removes assigned realm roles from user.

func (*UsersService) ResetPassword

func (s *UsersService) ResetPassword(ctx context.Context, realm, userID string, credential *Credential) (*http.Response, error)

ResetPassword sets or resets the user's password.

func (*UsersService) SendVerifyEmail

func (s *UsersService) SendVerifyEmail(ctx context.Context, realm, userID string, opts *VerifyEmailOptions) (*http.Response, error)

Send an email-verification email to the user. An email contains a link the user can click to verify their email address.

func (*UsersService) Update

func (s *UsersService) Update(ctx context.Context, realm string, user *User) (*http.Response, error)

Update update a single user.

type VerifyEmailOptions

type VerifyEmailOptions struct {
	ClientID    string `url:"client_id,omitempty"`
	RedirectUri string `url:"redirect_uri,omitempty"`
}

VerifyEmailOptions ...

Jump to

Keyboard shortcuts

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