gocloak

repository·main·Indexed 22 days ago

https://github.com/nerzal/gocloak

A Go client library for interacting with the Keycloak API. It provides high-level abstractions for authentication (OAuth2/OpenID Connect grants), token management, and administrative tasks including the management of users, groups, clients, realm roles, and protocol mappers.

Tokens
25.4K
Snippets
13
Records
73
Agent score
79%

What's inside gocloak

  1. Use GoCloakIface for dependency injection and mocking

    main
    The GoCloakIface interface defines the complete public API surface of the GoCloak client. Developers should use this interface instead of the concrete client type when writing code that depends on Keycloak, as it allows for easy mocking in unit tests and facilitates dependency injection.
  2. Handle Permission Tickets and Grants

    main

    Keycloak's permission system uses tickets and grants to manage resource access:

    1. Creating a Ticket: Use CreatePermissionTicketParams specifying ResourceID, ResourceScopes, and optional Claims.
    2. Permission Ticket Response: The server returns a PermissionTicketResponseRepresentation containing the Ticket string.
    3. Permission Ticket Content: The PermissionTicketRepresentation (which embeds jwt.RegisteredClaims) contains the AZP, Claims, and a list of PermissionTicketPermissionRepresentation (mapping scopes to resource IDs).
    4. Granting Permission: Use PermissionGrantParams to grant a specific ResourceID and ScopeName to a RequesterID using a TicketID.
  3. Work with Organization Members and Membership Types

    main

    Organizations in Keycloak use MembershipType to define how members relate to the organization:

    • MembershipTypeManaged: The member cannot exist without the organization.
    • MembershipTypeUnmanaged: The member can exist independently of the organization.

    Use MemberRepresentation to represent an organization member, which embeds the standard User type and includes the MembershipType.

    // MembershipType constants
    const (
        MembershipTypeManaged   MembershipType = "MANAGED"
        MembershipTypeUnmanaged MembershipType = "UNMANAGED"
    )
    
    type MemberRepresentation struct {
        User
        MembershipType *MembershipType `json:"membershipType,omitempty"`
    }
  4. Initialize a new GoCloak client

    main
    Use NewClient to create a new instance of the Keycloak adaptor. It requires the basePath (the root URL of your Keycloak server). You can provide optional functional configuration arguments to customize the client behavior, such as setting the server version or adjusting endpoint URLs.
  5. Run Keycloak and MailHog using Docker Compose

    main

    The project provides a docker-compose.yml file to set up a local development environment consisting of Keycloak and MailHog.

    Keycloak is configured in development mode (start-dev) with specific features enabled and an automatic realm import. MailHog is included to handle email testing.

    To run the environment, use the standard Docker Compose command:

  6. Configure GoCloak with Functional Options

    main

    When initializing NewClient, you can pass several functional options to override default configurations:

    • SetServerVersion(version string): Sets the Keycloak version to bypass the initial serverinfo call.
    • SetLegacyWildFlySupport(): Adjusts realm URL paths for older WildFly-based Keycloak installations.
    • SetAuthRealms(url string): Overrides the default auth realm path.
    • SetAuthAdminRealms(url string): Overrides the default admin realm path.
    • SetTokenEndpoint(url string): Overrides the OIDC token endpoint.
    • SetCertCacheInvalidationTime(duration time.Duration): Sets how long certificates are kept in the local cache.
  7. Configure Keycloak environment variables in Docker Compose

    main

    When using the provided docker-compose.yml, Keycloak is configured with the following environment variables:

    • KEYCLOAK_ADMIN: The initial admin username (set to admin).
    • KEYCLOAK_ADMIN_PASSWORD: The initial admin password (set to secret).
    • KC_HEALTH_ENABLED: Enables the health endpoint (set to "true").

    Keycloak is also configured to import a realm from a local file via the volume mapping: ./testdata/gocloak-realm.json:/opt/keycloak/data/import/gocloak-realm.json.

  8. Configure User Profile Attributes and Policies

    main

    The UserProfileConfig defines how user attributes are managed. It includes UserProfileAttribute definitions which specify:

    • Validations and Annotations (maps)
    • Required roles and scopes via UserProfileAttributeRequired
    • Permissions for viewing and editing via UserProfileAttributePermissions
    • Selector scopes via UserProfileAttributeSelector

    Unmanaged attributes are governed by UnmanagedAttributePolicy:

    • UnmanagedAttributePolicyEnabled: Unmanaged attributes can be used.
    • UnmanagedAttributePolicyAdminView: Unmanaged attributes are disabled and only visible to admins.
    • UnmanagedAttributePolicyAdminEdit: Unmanaged attributes can be viewed and edited only by admins.
  9. Manage Identity Providers in Keycloak

    main

    Use the following methods to manage Identity Providers (IDP) within a realm. Note that some methods require an admin token, while others might be used for importing configurations from URLs or files.

    • UpdateIdentityProvider: Updates an existing IDP.
    • DeleteIdentityProvider: Deletes an IDP in a realm.
    • ExportIDPPublicBrokerConfig: Exports the broker configuration for a specific alias.
    • ImportIdentityProviderConfig: Parses IDP config from a URL.
    • ImportIdentityProviderConfigFromFile: Parses IDP config from a file via an io.Reader.
    • CreateIdentityProviderMapper: Creates a mapper associated with an IDP alias.
    • GetIdentityProviderMapper: Retrieves a specific mapper by ID.
    • DeleteIdentityProviderMapper: Deletes a specific mapper.
    • GetIdentityProviderMappers: Lists all mappers for an IDP.
    • GetIdentityProviderMapperByID: Gets a mapper by its ID.
    • UpdateIdentityProviderMapper: Updates an existing mapper.
  10. Manage Client Protocol Mappers

    main

    Protocol mappers allow you to customize the tokens issued by a client. Use these methods to manage them within a client scope:

    • CreateClientProtocolMapper(ctx, token, realm, idOfClient, mapper): Creates a new protocol mapper. Returns the new mapper's ID.
    • UpdateClientProtocolMapper(ctx, token, realm, idOfClient, mapperID, mapper): Updates an existing mapper.
    • DeleteClientProtocolMapper(ctx, token, realm, idOfClient, mapperID): Deletes a mapper.
    • GetClientScopeProtocolMappers(ctx, token, realm, scopeID): Lists all mappers for a specific client scope.
    • GetClientScopeProtocolMapper(ctx, token, realm, scopeID, protocolMapperID): Retrieves a specific mapper by ID.
    • DeleteClientScopeProtocolMapper(ctx, token, realm, scopeID, protocolMapperID): Deletes a mapper from a client scope.
  11. Revoke a token

    main

    You can revoke an access or refresh token using the RevokeToken method. This requires client credentials (ID and Secret) and uses Basic Authentication.

    err := g.RevokeToken(ctx, realm, clientID, clientSecret, refreshToken)
  12. Manage Authentication Flows and Configurations

    main

    Configure how users authenticate within a realm by managing flows, executions, and authenticator configurations.

    Authentication Flows

    • GetAuthenticationFlows(ctx, token, realm): Lists all flows in a realm.
    • CreateAuthenticationFlow(ctx, token, realm, flow): Creates a new flow.
    • UpdateAuthenticationFlow(ctx, token, realm, flow, authenticationFlowID): Updates a flow.
    • DeleteAuthenticationFlow(ctx, token, realm, flowID): Deletes a flow.

    Executions and Configs

    • GetAuthenticationExecutions(ctx, token, realm, flow): Lists executions within a flow.
    • CreateAuthenticationExecution(ctx, token, realm, flow, execution): Adds an execution to a flow.
    • CreateAuthenticatorConfig(ctx, token, realm, config): Creates a new authenticator configuration and returns its ID.
    • GetAuthenticatorConfig(ctx, token, realm, configID): Retrieves a configuration by ID.
    • UpdateAuthenticatorConfig(ctx, token, realm, config, configID): Updates a configuration.