gocloak

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Feb 15, 2019 License: Apache-2.0 Imports: 9 Imported by: 13

README

gocloak

codebeat badge Go Report Card Go Doc

golang keycloak client

This client is based on : go-keycloak

For Questions either raise an issue, or come to the gopher-slack into the channel #gocloak

If u are using the echo framework have a look at gocloak-echo

Keycloak Version < 4.8

If you are using a Keycloak Server version <4.8 please use the V1.0 release of keycloak.

	go get gopkg.in/nerzal/gocloak.v1
	import "gopkg.in/nerzal/gocloak.v1"

https://gopkg.in/nerzal/gocloak.v1

Usage

Create New User
	gocloak := gocloak.NewClient("https://mycool.keycloak.instance")
	token, err := gocloak.LoginAdmin("user", "password", "realmName")
	if err != nil {
		panic("Something wrong with the credentials or url")
	}
	user := gocloak.User{
		FirstName: "Bob",
		LastName:  "Uncle",
		EMail:     "something@really.wrong",
		Enabled:   true,
		Username:  "CoolGuy",
	}
	gocloak.CreateUser(token.AccessToken, "realm", user)
	if err != nil {
		panic("Oh no!, failed to create user :(")
	}
Introspect Token
	client := NewClient(hostname)
	token, err := client.LoginClient(clientid, clientSecret, realm)
	if err != nil {
		panic("Login failed:"+ err.Error())
	}

	rptResult, err := client.RetrospectToken(token.AccessToken, clientid, clientSecret, realm)
	if err != nil {
		panic("Inspection failed:"+ err.Error())
	}

	if !rptResult.Active {
		panic("Token is not active")
	}

	permissions := rptResult.Permissions
	//Do something with the permissions ;) 

Features

// GoCloak holds all methods a client should fullfill
type GoCloak interface {
	Login(clientID string, clientSecret string, realm string, username string, password string) (*JWT, error)
	LoginClient(clientID, clientSecret, realm string) (*JWT, error)
	LoginAdmin(username, password, realm string) (*JWT, error)
	RequestPermission(clientID string, clientSecret string, realm string, username string, password string, permission string) (*JWT, error)
	RefreshToken(refreshToken string, clientID, clientSecret, realm string) (*JWT, error)
	DecodeAccessToken(accessToken string, realm string) (*jwt.Token, *jwt.MapClaims, error)
	DecodeAccessTokenCustomClaims(accessToken string, realm string, claims jwt.Claims) (*jwt.Token, error)
	RetrospectToken(accessToken string, clientID, clientSecret string, realm string) (*RetrospecTokenResult, error)

	GetIssuer(realm string) (*IssuerResponse, error)
	GetCerts(realm string) (*CertResponse, error)

	SetPassword(token string, userID string, realm string, password string, temporary bool) error
	CreateUser(token string, realm string, user User) (*string, error)
	CreateGroup(accessToken string, realm string, group Group) error
	CreateRole(accessToken string, realm string, clientID string, role Role) error
	CreateClient(accessToken string, realm string, clientID Client) error
	CreateClientScope(accessToken string, realm string, scope ClientScope) error
	CreateComponent(accessToken string, realm string, component Component) error

	UpdateUser(accessToken string, realm string, user User) error
	UpdateGroup(accessToken string, realm string, group Group) error
	UpdateRole(accessToken string, realm string, clientID string, role Role) error
	UpdateClient(accessToken string, realm string, clientID Client) error
	UpdateClientScope(accessToken string, realm string, scope ClientScope) error

	DeleteUser(accessToken string, realm, userID string) error
	DeleteComponent(accessToken string, realm, componentID string) error
	DeleteGroup(accessToken string, realm, groupID string) error
	DeleteRole(accessToken string, realm, clientID, roleName string) error
	DeleteClient(accessToken string, realm, clientID string) error
	DeleteClientScope(accessToken string, realm, scopeID string) error

	GetKeyStoreConfig(accessToken string, realm string) (*KeyStoreConfig, error)
	GetUserByID(accessToken string, realm string, userID string) (*User, error)
	GetUserCount(accessToken string, realm string) (int, error)
	GetUsers(accessToken string, realm string) (*[]User, error)
	GetUserGroups(accessToken string, realm string, userID string) (*[]UserGroup, error)
	GetComponents(accessToken string, realm string) (*[]Component, error)

	UserAttributeContains(attributes map[string][]string, attribute string, value string) bool

	GetGroups(accessToken string, realm string) (*[]Group, error)
	GetGroup(accessToken string, realm, groupID string) (*Group, error)
	GetRoles(accessToken string, realm string) (*[]Role, error)
	GetRoleMappingByGroupID(accessToken string, realm string, groupID string) (*[]RoleMapping, error)
	GetRoleMappingByUserID(accessToken string, realm string, userID string) (*[]RoleMapping, error)
	GetRolesByClientID(accessToken string, realm string, clientID string) (*[]Role, error)
	GetClients(accessToken string, realm string) (*[]Client, error)
	GetRealmRolesByUserID(accessToken string, realm string, userID string) (*[]Role, error)
	GetRealmRolesByGroupID(accessToken string, realm string, groupID string) (*[]Role, error)
	GetUsersByRoleName(token string, realm string, roleName string) (*[]User, error)
}

developing & testing

I was to lazy to add some environment variables. So i added a "super.secret.go" file, which holds some constants(username, password, realm), that are used for the tests.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type APIError

type APIError struct {
	Code    int
	Message string
}

APIError represents an api error

func (APIError) Error

func (apiError APIError) Error() string

Error stringifies the APIError

type Access

type Access struct {
	ManageGroupMembership bool `json:"manageGroupMembership"`
	View                  bool `json:"view"`
	MapRoles              bool `json:"mapRoles"`
	Impersonate           bool `json:"impersonate"`
	Manage                bool `json:"manage"`
}

Access represents access

type ActiveKeys

type ActiveKeys struct {
	HS256 string `json:"HS256"`
	RS256 string `json:"RS256"`
	AES   string `json:"AES"`
}

ActiveKeys holds the active keys

type Attributes

type Attributes struct {
	LDAPENTRYDN []string `json:"LDAP_ENTRY_DN"`
	LDAPID      []string `json:"LDAP_ID"`
}

Attributes holds Attributes

type CertResponse

type CertResponse struct {
	Keys []CertResponseKey `json:"keys"`
}

CertResponse is retuned by the certs endpoint

type CertResponseKey

type CertResponseKey struct {
	Kid string `json:"kid"`
	Kty string `json:"kty"`
	Alg string `json:"alg"`
	Use string `json:"use"`
	N   string `json:"n"`
	E   string `json:"e"`
}

type Client

type Client struct {
	ID       string `json:"id"`
	ClientID string `json:"clientId"`
}

Client is a Client

type ClientRoleMappingRole

type ClientRoleMappingRole struct {
	ID                 string `json:"id"`
	Name               string `json:"name"`
	Description        string `json:"description,omitempty"`
	ScopeParamRequired bool   `json:"scopeParamRequired"`
	Composite          bool   `json:"composite"`
	ClientRole         bool   `json:"clientRole"`
	ContainerID        string `json:"containerId"`
}

ClientRoleMappingRole is a client role mapping role

type ClientScope

type ClientScope struct {
	ID                    string                `json:"id"`
	Name                  string                `json:"name"`
	Description           string                `json:"description"`
	Protocol              string                `json:"protocol"`
	ClientScopeAttributes ClientScopeAttributes `json:"attributes"`
	ProtocolMappers       ProtocolMappers       `json:"protocolMappers,omitempty"`
}

ClientScope is a ClientScope

type ClientScopeAttributes

type ClientScopeAttributes struct {
	ConsentScreenText      string `json:"consent.screen.text"`
	DisplayOnConsentScreen string `json:"display.on.consent.screen"`
}

ClientScopeAttributes are attributes of client scopes

type Component

type Component struct {
	ID              string          `json:"id"`
	Name            string          `json:"name"`
	ProviderID      string          `json:"providerId"`
	ProviderType    string          `json:"providerType"`
	ParentID        string          `json:"parentId"`
	ComponentConfig ComponentConfig `json:"config"`
	SubType         string          `json:"subType,omitempty"`
}

Component is a component

type ComponentConfig

type ComponentConfig struct {
	Priority  []string `json:"priority"`
	Algorithm []string `json:"algorithm"`
}

ComponentConfig is a componentconfig

type GoCloak

type GoCloak interface {
	// Login sends a request to the token endpoint using user and client credentials
	Login(clientID string, clientSecret string, realm string, username string, password string) (*JWT, error)
	// LoginClient sends a request to the token endpoint using client credentials
	LoginClient(clientID, clientSecret, realm string) (*JWT, error)
	// LoginAdmin login as admin
	LoginAdmin(username, password, realm string) (*JWT, error)
	// RequestPermisssion sends a request to the token endpoint with permission parameter
	RequestPermission(clientID string, clientSecret string, realm string, username string, password string, permission string) (*JWT, error)
	// RefreshToken used to refresh the token
	RefreshToken(refreshToken string, clientID, clientSecret, realm string) (*JWT, error)
	// DecodeAccessToken decodes the accessToken
	DecodeAccessToken(accessToken string, realm string) (*jwt.Token, *jwt.MapClaims, error)
	// DecodeAccessTokenCustomClaims decodes the accessToken and fills the given claims
	DecodeAccessTokenCustomClaims(accessToken string, realm string, claims jwt.Claims) (*jwt.Token, error)
	// DecodeAccessTokenCustomClaims calls the token introspection endpoint
	RetrospectToken(accessToken string, clientID, clientSecret string, realm string) (*RetrospecTokenResult, error)
	// GetIssuer calls the issuer endpoint for the given realm
	GetIssuer(realm string) (*IssuerResponse, error)
	// GetCerts gets the public keys for the given realm
	GetCerts(realm string) (*CertResponse, error)

	//SetPassword sets a new password for the user with the given id. Needs elevated priviliges
	SetPassword(token string, userID string, realm string, password string, temporary bool) error

	// CreateUser creates a new user
	CreateUser(token string, realm string, user User) (*string, error)
	// CreateGroup creates a new group
	CreateGroup(accessToken string, realm string, group Group) error
	// CreateRole creates a new role
	CreateRole(accessToken string, realm string, clientID string, role Role) error
	// CreateClient creates a new client
	CreateClient(accessToken string, realm string, clientID Client) error
	// CreateClientScope creates a new clientScope
	CreateClientScope(accessToken string, realm string, scope ClientScope) error
	// CreateComponent creates a new component
	CreateComponent(accessToken string, realm string, component Component) error

	// UpdateUser updates the given user
	UpdateUser(accessToken string, realm string, user User) error
	// UpdateGroup updates the given group
	UpdateGroup(accessToken string, realm string, group Group) error
	// UpdateRole updates the given role
	UpdateRole(accessToken string, realm string, clientID string, role Role) error
	// UpdateClient updates the given client
	UpdateClient(accessToken string, realm string, clientID Client) error
	// UpdateClientScope updates the given clientScope
	UpdateClientScope(accessToken string, realm string, scope ClientScope) error

	// DeleteUser deletes the given user
	DeleteUser(accessToken string, realm, userID string) error
	// DeleteComponent deletes the given component
	DeleteComponent(accessToken string, realm, componentID string) error
	// DeleteGroup deletes the given group
	DeleteGroup(accessToken string, realm, groupID string) error
	// DeleteRole deletes the given role
	DeleteRole(accessToken string, realm, clientID, roleName string) error
	// DeleteClient deletes the given client
	DeleteClient(accessToken string, realm, clientID string) error
	// DeleteClientScope
	DeleteClientScope(accessToken string, realm, scopeID string) error

	// GetKeyStoreConfig gets the keyStoreConfig
	GetKeyStoreConfig(accessToken string, realm string) (*KeyStoreConfig, error)
	// GetUserByID gets the user with the given id
	GetUserByID(accessToken string, realm string, userID string) (*User, error)
	// GetUser count returns the userCount of the given realm
	GetUserCount(accessToken string, realm string) (int, error)
	// GetUsers gets all users of the given realm
	GetUsers(accessToken string, realm string) (*[]User, error)
	// GetUserGroups gets the groups of the given user
	GetUserGroups(accessToken string, realm string, userID string) (*[]UserGroup, error)
	// GetComponents gets components of the given realm
	GetComponents(accessToken string, realm string) (*[]Component, error)
	// GetGroups gets all groups of the given realm
	GetGroups(accessToken string, realm string) (*[]Group, error)
	// GetGroup gets the given group
	GetGroup(accessToken string, realm, groupID string) (*Group, error)
	// GetRoles get all roles of the given realm
	GetRoles(accessToken string, realm string) (*[]Role, error)
	// GetRoleMappingByGroupID gets the rolemapping for the given group id
	GetRoleMappingByGroupID(accessToken string, realm string, groupID string) (*[]RoleMapping, error)
	// GetRoleMappingByUserID gets the rolemapping for the given user id
	GetRoleMappingByUserID(accessToken string, realm string, userID string) (*[]RoleMapping, error)
	// GetRolesByClientID gets roles for the given client
	GetRolesByClientID(accessToken string, realm string, clientID string) (*[]Role, error)
	// GetClients gets the clients in the realm
	GetClients(accessToken string, realm string) (*[]Client, error)
	// GetRealmRolesByUserID gets roles for the given uerID
	GetRealmRolesByUserID(accessToken string, realm string, userID string) (*[]Role, error)
	// GetRealmRolesByGroupID gets roles for given groupID
	GetRealmRolesByGroupID(accessToken string, realm string, groupID string) (*[]Role, error)
	// GetUsersByRoleName gets users for given roleName
	GetUsersByRoleName(token string, realm string, roleName string) (*[]User, error)

	// UserAttributeContains checks if the given attribute has the given value
	UserAttributeContains(attributes map[string][]string, attribute string, value string) bool
}

GoCloak holds all methods a client should fullfill

func NewClient

func NewClient(basePath string) GoCloak

NewClient creates a new Client

type Group

type Group struct {
	ID        string        `json:"id,omitempty"`
	Name      string        `json:"name,omitempty"`
	Path      string        `json:"path,omitempty"`
	SubGroups []interface{} `json:"subGroups,omitempty"`
}

Group is a Group

type IssuerResponse

type IssuerResponse struct {
	Realm           string `json:"realm"`
	PublicKey       string `json:"public_key"`
	TokenService    string `json:"token-service"`
	AccountService  string `json:"account-service"`
	TokensNotBefore int    `json:"tokens-not-before"`
}

IssuerResponse is returned by the issuer endpoint

type JWT

type JWT struct {
	AccessToken      string `json:"access_token"`
	ExpiresIn        int    `json:"expires_in"`
	RefreshExpiresIn int    `json:"refresh_expires_in"`
	RefreshToken     string `json:"refresh_token"`
	TokenType        string `json:"token_type"`
	NotBeforePolicy  int    `json:"not-before-policy"`
	SessionState     string `json:"session_state"`
	Scope            string `json:"scope"`
}

JWT is a JWT

type Key

type Key struct {
	ProviderID       string `json:"providerId"`
	ProviderPriority int    `json:"providerPriority"`
	Kid              string `json:"kid"`
	Status           string `json:"status"`
	Type             string `json:"type"`
	Algorithm        string `json:"algorithm"`
	PublicKey        string `json:"publicKey,omitempty"`
	Certificate      string `json:"certificate,omitempty"`
}

Key is a key

type KeyStoreConfig

type KeyStoreConfig struct {
	ActiveKeys ActiveKeys `json:"active"`
	Key        []Key      `json:"keys"`
}

KeyStoreConfig holds the keyStoreConfig

type ObjectAllreadyExists

type ObjectAllreadyExists struct{}

ObjectAllreadyExists is used when keycloak answers with 409

func (*ObjectAllreadyExists) Error

func (o *ObjectAllreadyExists) Error() string

type ProtocolMappers

type ProtocolMappers struct {
	ID                    string                `json:"id"`
	Name                  string                `json:"name"`
	Protocol              string                `json:"protocol"`
	ProtocolMapper        string                `json:"protocolMapper"`
	ConsentRequired       bool                  `json:"consentRequired"`
	ProtocolMappersConfig ProtocolMappersConfig `json:"config"`
}

ProtocolMappers are protocolmappers

type ProtocolMappersConfig

type ProtocolMappersConfig struct {
	UserinfoTokenClaim string `json:"userinfo.token.claim"`
	UserAttribute      string `json:"user.attribute"`
	IDTokenClaim       string `json:"id.token.claim"`
	AccessTokenClaim   string `json:"access.token.claim"`
	ClaimName          string `json:"claim.name"`
	JSONTypeLabel      string `json:"jsonType.label"`
}

ProtocolMappersConfig is a config of a protocol mapper

type RetrospecTokenResult

type RetrospecTokenResult struct {
	Permissions map[string]string `json:"permissions,omitempty"`
	Exp         int               `json:"exp,omitempty"`
	Nbf         int               `json:"nbf,omitempty"`
	Iat         int               `json:"iat,omitempty"`
	Aud         string            `json:"aud,omitempty"`
	Active      bool              `json:"active,omitempty"`
	AuthTime    int               `json:"auth_time,omitempty"`
	Jti         string            `json:"jti,omitempty"`
	Type        string            `json:"typ,omitempty"`
}

RetrospecTokenResult is returned when a token was checked

type Role

type Role struct {
	ID                 string `json:"id,omitempty"`
	Name               string `json:"name,omitempty"`
	ScopeParamRequired bool   `json:"scopeParamRequired,omitempty"`
	Composite          bool   `json:"composite,omitempty"`
	ClientRole         bool   `json:"clientRole,omitempty"`
	ContainerID        string `json:"containerId,omitempty"`
	Description        string `json:"description,omitempty,omitempty"`
}

Role is a role

type RoleMapping

type RoleMapping struct {
	ID       string                  `json:"id"`
	Client   string                  `json:"client"`
	Mappings []ClientRoleMappingRole `json:"mappings"`
}

RoleMapping is a role mapping

type SetPasswordRequest

type SetPasswordRequest struct {
	Type      string `json:"type"`
	Temporary bool   `json:"temporary"`
	Password  string `json:"value"`
}

SetPasswordRequest sets a new password

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"`
	FederationLink             string              `json:"federationLink,omitempty"`
	Attributes                 map[string][]string `json:"attributes,omitempty"`
	DisableableCredentialTypes []interface{}       `json:"disableableCredentialTypes,omitempty"`
	RequiredActions            []interface{}       `json:"requiredActions,omitempty"`
	Access                     map[string]bool     `json:"access,omitempty"`
}

User represents the Keycloak User Structure

type UserGroup

type UserGroup struct {
	ID   string `json:"id,omitempty"`
	Name string `json:"name,omitempty"`
	Path string `json:"path,omitempty"`
}

UserGroup is a UserGroup

Directories

Path Synopsis
pkg
jwx

Jump to

Keyboard shortcuts

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