8.4.633-stable Switch to dev

External SSO

Introduction

GreyCat signs users in through any Single Sign-On (SSO) provider that implements OpenID Connect (OIDC), such as Keycloak, Microsoft Entra ID or Google. Your organization keeps managing its accounts in its own identity provider, and each provider user signs in to GreyCat as a GreyCat Identity.

SSO is provided by the openid library (a GreyCat Pro license is required). It supports several providers at once and offers two ways to sign in:

  • Redirect flow, driven by the server. The browser is sent to the provider and comes back to GreyCat with an authorization code. GreyCat runs the OAuth 2.0 Authorization Code flow with PKCE itself, verifies the ID token (state, nonce, signature, iss, aud, exp), resolves it to a runtime::Identity and sets the greycat session cookie.
  • Token exchange. A client that already holds an ID token (a mobile app, a CLI, a single-page app using a provider SDK) calls Openid::token_login(provider, jwt) to trade it for a GreyCat session.

The rest of this page describes the GreyCat side first, then walks through the configuration of Keycloak, Microsoft Entra ID and Google.

Installation

Add the library to your project:

greycat install openid

This writes the @library pragma into project.gcl and downloads the library into lib/openid/. You can also write the pragma yourself and run greycat install:

@library("std", "0.0.0");
@library("openid", "0.0.0");

Registering a provider

A provider is described by an OidcProvider and registered under an id of your choice with Openid::register. Registrations are held in memory only, so they must run on every server start. Do it from main, which greycat serve runs as a startup task.

fn main() {
    Openid::register("google", OidcProvider {
        issuer: "https://accounts.google.com",
        client_id: System::getEnv("GOOGLE_CLIENT_ID")!!,
        client_secret: System::getEnv("GOOGLE_CLIENT_SECRET"),
        scopes: ["openid", "email", "profile"],
        redirect_uri: "http://localhost:8080/",
    });
}

Keep the client secret out of the source code. System::getEnv reads it from the process environment, which GreyCat also fills from a .env file in the project directory:

GOOGLE_CLIENT_ID=1234567890-abc.apps.googleusercontent.com
GOOGLE_CLIENT_SECRET=GOCSPX-...

When a variable is missing, main fails and the provider is not registered, but the server keeps running. Check the startup log if a provider does not show up.

The fields of OidcProvider:

Field Description
issuer Issuer URL of the provider. It must match the iss claim of its tokens. GreyCat discovers the endpoints and signing keys from <issuer>/.well-known/openid-configuration.
client_id Client ID registered with the provider.
client_secret Client secret. null for a public client (PKCE only).
scopes Scopes to request. They must include openid. Defaults to ["openid", "email", "profile"].
redirect_uri Absolute redirect URI, exactly as registered with the provider. Point it at the root of your site, with the trailing /.
audience Optional audience to check the aud claim against. Defaults to client_id.
auto_create_identity When true, a provider user without a matching Identity gets one, with role user. Defaults to false. Ignored when a hook is set (see below).

Discovery documents and signing keys are cached for an hour and refreshed when a token is signed with an unknown key, so key rotation needs no restart. Supported signing algorithms are RS256/384/512, ES256/384/512 and PS256/384/512.

The sign-in flow

With redirect_uri set to the site root, nothing else is needed on the frontend. GreyCat serves a built-in index.html at / that offers the password login and a button for each registered provider. A click on a provider button calls Openid::login, which returns the authorization URL of the provider, and the browser goes there. After the user signs in, the provider redirects the browser back to the same page with ?code=...&state=.... The page passes them to Openid::callback, which exchanges the code for the tokens, verifies the ID token, resolves the Identity and sets the greycat cookie.

A webroot/index.html of your own replaces the built-in page. A web app built on @greycat/web gets the same flow from the SDK by passing the provider id to init:

const result = await gc.sdk.init({ auth: { openid: "keycloak" } });

init either finds a session, finishes a redirect coming back from the provider, or sends the browser to the provider. The pending-login state (state, nonce, PKCE verifier, return URL) is kept in memory for about 5 minutes, and a single GreyCat process is assumed.

All the endpoints of the library are public, since they serve callers that are not signed in yet:

Endpoint Description
Openid::providers() Ids of the registered providers, for a login page.
Openid::public_config(id) issuer, client_id, redirect_uri and scopes of a provider. It never contains the secret.
Openid::login(provider_id, return_to) Starts the redirect flow and returns the authorization URL.
Openid::callback(code, state) Finishes the redirect flow and returns the return_to given to login.
Openid::token_login(provider_id, jwt) Verifies an ID token and signs its user in.
Openid::end_session_url(provider_id, id_token_hint, post_logout_redirect_uri) Logout URL of the provider, or null when it has no end_session_endpoint.

Token exchange

For the token-exchange flow, the browser runs the Authorization Code flow with PKCE against the provider itself, then hands the ID token to Openid::token_login. @greycat/web does this with gc.sdk.init({ auth: { openidPkce: "keycloak" } }) or with the gc.sdk.OpenidClient class. The OAuth client must then be a public client (no secret), and the authorization, token and JWKS endpoints of the provider must allow CORS from your frontend origin. Prefer the redirect flow unless you need this one.

From provider user to Identity

Each sign-in ends with a GreyCat Identity (see Permissions and Authentication). Without a hook, OpenidHelpers::default_match picks it:

  1. A subject (sub, the permanent id of the user at the provider) that signed in before signs in as the same Identity, whatever its username and email say now. A user renamed at the provider, or whose username changes case, keeps their Identity.
  2. Otherwise, preferred_username and then email are looked up with Identity::get_by_name, which ignores case and Unicode normalization. The email is skipped when the provider sends email_verified: false. With auto_create_identity: true, an unknown name is created with role user. Otherwise the login is rejected.
  3. The Identity found is bound to the subject. A login whose name matches an Identity already bound to another subject of the same provider is rejected, since another account at the provider claims that name. When a user’s account was recreated at the provider, hand the Identity over with OpenidHelpers::unbind(provider_id, identity).

With the default and auto_create_identity left off, only users that already exist in GreyCat may sign in. Create them ahead with greycat user add <name> [role] or Identity::create.

Hooks

Openid::set_hook replaces default_match with a function of your own. It receives the provider id and an OidcResult, and returns the Identity to sign in as, or null to reject the login:

fn domain_hook(provider_id: String, r: OidcResult): Identity? {
    var email = r.claims.email;
    if (email == null || r.claims.email_verified != true || !email.endsWith("@example.com")) {
        return null;
    }
    var identity = OpenidHelpers::bound(provider_id, r.claims.sub) ?? OpenidHelpers::ensure(email, "user");
    if (identity == null || !OpenidHelpers::bind(provider_id, r.claims.sub, identity)) {
        return null;
    }
    return identity;
}

fn main() {
    Openid::register("google", OidcProvider {
        issuer: "https://accounts.google.com",
        client_id: System::getEnv("GOOGLE_CLIENT_ID")!!,
        client_secret: System::getEnv("GOOGLE_CLIENT_SECRET"),
        redirect_uri: "http://localhost:8080/",
    });
    Openid::set_hook(domain_hook);
}

r.claims holds the verified claims of the ID token (sub, iss, aud, exp, iat, email, email_verified, name, preferred_username, groups), and r.claims.raw every claim as a map. r.id_token is the raw ID token. r.access_token and r.refresh_token are set by the redirect flow and are null under token_login. All three are bearer credentials, so never log an OidcResult. Log r.claims.sub to trace a login.

A hook that throws fails the login, and the user has to start over. Reject a login by returning null. The OpenidHelpers type gives the building blocks:

Helper Description
default_match(provider_id, r) The default resolver described above.
ensure(name, role) Finds or creates the Identity. role applies only when it is created.
ensure_role(name, role) Finds or creates the Identity and sets its role, so the role is applied again on every login.
bound(provider_id, sub) The Identity a subject is bound to, or null.
bind(provider_id, sub, identity) Binds a subject to an Identity. Returns false when the Identity is bound to another subject of the provider.
unbind(provider_id, identity) Releases an Identity from its subject.
sync_role(identity, role) Sets the role without ever throwing. Returns false when the role could not be applied.
stable_name(provider_id, claims) A collision-proof name such as google:1234567890, built from sub.
role_from_groups(groups, mapping, default_role) The first role of mapping matching one of groups, or default_role.

Providers anyone can sign in with

On a provider open to the public (Google accounts, multi-tenant Entra ID), auto_create_identity lets a stranger take a name first, after which its real owner is rejected. Restrict who may sign in, as domain_hook does above, or name the Identities after the subject with stable_name:

fn open_provider_hook(provider_id: String, r: OidcResult): Identity? {
    var identity = OpenidHelpers::bound(provider_id, r.claims.sub)
        ?? OpenidHelpers::ensure(OpenidHelpers::stable_name(provider_id, r.claims), "user");
    if (identity == null || !OpenidHelpers::bind(provider_id, r.claims.sub, identity)) {
        return null;
    }
    return identity;
}

fn main() {
    Openid::set_hook(open_provider_hook);
}

Microsoft Entra ID sends no email_verified, and a multi-tenant app can receive any email from another tenant. Match Entra users on preferred_username, or check r.claims.raw in a hook.

Roles

An Identity has exactly one role, and the permissions of the role are read on every request. Roles are declared in GCL with @role, next to the built-in public, user and admin:

@library("std", "0.0.0");
@library("openid", "0.0.0");

@include("src");

@role("analyst", "public", "api");

To keep the provider in charge of roles, map them in a hook and apply the result with ensure_role on every login. The hook below reads the roles claim of the ID token, which is where both the Keycloak mapper and the Entra app roles described below put them. It rejects users holding none of the mapped roles:

/// The values of the `roles` claim of the ID token. A provider sends one string
/// or an array of strings, depending on its configuration.
fn roles_claim(r: OidcResult): Array<String> {
    var roles = Array<String> {};
    var value = r.claims.raw.get("roles");
    if (value is String) {
        roles.add(value);
    } else if (value is Array<any?>) {
        for (_, v in value) {
            if (v is String) {
                roles.add(v);
            }
        }
    }
    return roles;
}

/// Signs a user in with the GreyCat role matching their provider role, and
/// rejects users who hold none of the mapped roles.
fn role_hook(provider_id: String, r: OidcResult): Identity? {
    var mapping = Map<String, String> {};
    mapping.set("admin", "admin");
    mapping.set("analyst", "analyst");
    mapping.set("user", "user");

    var role = OpenidHelpers::role_from_groups(roles_claim(r), mapping, "");
    if (role == "") {
        return null;
    }
    // A known subject keeps its Identity, even after a rename at the provider.
    var name = OpenidHelpers::bound(provider_id, r.claims.sub)?.name ?? r.claims.preferred_username;
    if (name == null) {
        return null;
    }
    var identity = OpenidHelpers::ensure_role(name, role);
    if (identity == null || !OpenidHelpers::bind(provider_id, r.claims.sub, identity)) {
        return null;
    }
    return identity;
}

Map only to roles declared with @role. Creating an Identity with an unknown role throws, and a throwing hook fails the login. ensure would apply the role only when the Identity is created, leaving a user whose provider roles changed on their first role. When the provider puts the roles in a groups claim instead, pass r.claims.groups to role_from_groups directly.

r.claims only covers the ID token. Keycloak’s built-in role mappers do not add roles to the ID token, so on a realm without a dedicated mapper the roles are only in the access token. Either add a mapper (see Include roles in the ID token) or decode r.access_token in the hook.

Sessions and logout

A successful login sets the greycat cookie, which holds a GreyCat session token. Its lifetime is the --validity option of greycat serve (GREYCAT_VALIDITY, 24 hours by default), independent of the tokens of the provider. The role of the Identity is read on every request, while the hook only runs at login. A role changed at the provider therefore applies at the next login of the user.

Logging out takes two steps. runtime::Identity::logout clears the GreyCat session. Openid::end_session_url(provider_id, id_token_hint, post_logout_redirect_uri) returns the logout URL of the provider, which ends the session there too when the browser is sent to it. OpenidClient.logout() in @greycat/web does both for the token-exchange flow.

FAQs

  • Did the authentication work? A successful login stores a cookie named greycat in the browser. Check it with the developer tools of your browser. greycat token
  • Why is my login rejected after signing in at the provider? The ID token was valid but no Identity was found for it. With the default resolver, the user must exist in GreyCat under its preferred_username or verified email, unless auto_create_identity is on. With role_hook, the user must hold one of the mapped roles and the ID token must carry them. Also check that no other subject of the same provider is bound to that Identity.
  • Why do I get 403 Forbidden once signed in? The role of the Identity lacks the permission of the function called. A public role only reaches public endpoints. Give the Identity a role with api, or fix the role mapping.
  • Why do I get a redirect_uri_mismatch error? The redirect_uri sent by GreyCat differs from the one registered at the provider. They must match exactly, including the trailing /. If GreyCat runs at http://localhost:8080, register http://localhost:8080/.

Using Keycloak

[Back to the beginning]

Launch Keycloak service

If a Keycloak service is already available to you, skip to Create client. Otherwise, the simplest way to get one for a demo is Docker.

Install Docker

According to the official documentation, “Docker is an open platform for developing, shipping, and running applications. Docker enables you to separate your applications from your infrastructure so you can deliver software quickly”. If you’re unfamiliar with Docker’s basic concepts, refer to this link: https://docs.docker.com/get-started/overview/

If Docker is not installed on your machine yet, install it for your platform:

  • Linux: Install Docker Engine directly, without Docker Desktop. See the installation guide: https://docs.docker.com/engine/install/
  • Windows or Mac: Install Docker Desktop, which includes Docker Engine:
    • Windows: https://docs.docker.com/desktop/install/windows-install/
    • MacOS: https://docs.docker.com/desktop/install/mac-install/

Starting a Keycloak instance with Docker

The command below starts Keycloak on port 5000 with the administrator admin and the password admin (for testing purposes only). Docker fetches the Keycloak image if it is not on your machine yet.

docker run -p 5000:8080 -e KEYCLOAK_ADMIN=admin -e KEYCLOAK_ADMIN_PASSWORD=admin quay.io/keycloak/keycloak:23.0.7 start-dev

The output looks like this:

$ docker run -p 5000:8080 -e KEYCLOAK_ADMIN=admin -e KEYCLOAK_ADMIN_PASSWORD=admin quay.io/keycloak/keycloak:23.0.7 start-dev
Updating the configuration and installing your custom providers, if any. Please wait.
2024-03-01 13:44:25,910 INFO  [io.quarkus.deployment.QuarkusAugmentor] (main) Quarkus augmentation completed in 5220ms
...
2024-03-01 13:44:38,423 INFO  [org.keycloak.services] (main) KC-SERVICES0009: Added user 'admin' to realm 'master'
2024-03-01 13:44:38,426 WARN  [org.keycloak.quarkus.runtime.KeycloakMain] (main) Running the server in development mode. DO NOT use this configuration in production.

Configure the Keycloak service

Create realm

Open http://localhost:5000/admin/master/console/ and sign in with admin and admin. The master realm is displayed by default. Create a new realm named Datathings from the dropdown button in the top left corner.

create realm

The realm only needs a name.

creating realm

Create client

In the Datathings realm, create a client for the GreyCat application. Open Clients in the left panel and click Create client.

create client

General settings

Name the client DemoGreyCat and keep OpenID Connect as the client type.

client general settings

Capability configuration

Under Capability configuration, set:

  • Client authentication: On. This makes a confidential client with a client secret, as the redirect flow expects.
  • Authorization: Off
  • Authentication flow: Standard flow. GreyCat uses the Authorization Code flow, so Implicit flow and Direct access grants (checked in the screenshot) can stay unchecked.

client capability setting

Login settings

Under Login settings, set:

  • Root URL: http://localhost:8080
  • Valid redirect URIs: http://localhost:8080/, the redirect_uri given to Openid::register.

The screenshot uses * for the redirect URIs and web origins, which accepts any value. Never use * in production. Web origins only matter for the token-exchange flow, where the browser calls Keycloak directly.

client login settings

Client secret

Once the client is created, open its Credentials tab and copy the Client secret. GreyCat reads it from the KEYCLOAK_CLIENT_SECRET environment variable below.

GreyCat maps Keycloak roles to its own roles through role_hook. Each Keycloak role name used in the mapping must match a key of the mapping in the hook, and each value of that mapping must be a GreyCat role (admin, user or one declared with @role). Roles can be defined at two levels, and only the role name matters.

Define realm roles

Realm roles are visible to every client of the realm. Define them from Realm roles in the left panel.

realm role

Define client roles

Client roles are only visible to their client by default. Define them from Clients, select your client and open the Roles tab.

client role

Role assignment

Create a user

Create a user from Users in the left panel. role_hook names the GreyCat Identity after the Keycloak username (preferred_username). The default resolver also tries the email, so fill the Email field when relying on it.

Jane Doe

Define credentials

Open the Credentials tab of the user and set a password.

Jane Doe

Define role mapping

Open the Role mapping tab of the user and assign a role. The dialog lets you choose between realm roles and client roles. This example assigns the client role admin.

role assignment

Include roles in the ID token

Keycloak does not put the roles of a user in the ID token by default, and role_hook reads them from there. Add a mapper to the dedicated client scope:

  • Open Clients in the left panel and click the DemoGreyCat client.
  • Open its Client scopes tab.
  • Click the scope dedicated to the client, DemoGreyCat-dedicated.

client scopes

Click Configure a new mapper and choose User Client Role for client roles, or User Realm Role for realm roles.

mapper info

Configure the mapper as follows:

  • Client ID: your client, DemoGreyCat, for a User Client Role mapper.
  • Multivalued: On. The claim is then an array, and role_from_groups keeps the first role of the mapping that the user holds.
  • Token Claim Name: roles, the claim roles_claim reads. Naming it groups instead fills r.claims.groups.
  • Claim JSON Type: String
  • Add to ID token: On

mapper detail

GreyCat configuration

Two values come from Keycloak:

  • The realm id, in Realm settings, tab General. The issuer is http://<keycloak host>/realms/<realm id>. Realm ID
  • The client id, in the list of Clients. client ID

Put the client secret in the .env file of your project:

KEYCLOAK_CLIENT_SECRET=<the client secret>

Then register the provider and the role hook:

fn main() {
    Openid::register("keycloak", OidcProvider {
        issuer: "http://localhost:5000/realms/Datathings",
        client_id: "DemoGreyCat",
        client_secret: System::getEnv("KEYCLOAK_CLIENT_SECRET"),
        redirect_uri: "http://localhost:8080/",
    });
    Openid::set_hook(role_hook);
}

Start GreyCat with greycat serve, open http://localhost:8080/ and choose keycloak on the sign-in page.

Using Microsoft Entra ID

[Back to the beginning]

Application registration

The entry for registration

Sign in to the Microsoft Entra admin center with your organization account. In the left menu, open Applications -> App registrations and click New registration.

registration entry

Registration

Provide:

  • The name of the application.
  • The supported account types. Choose Accounts in this organizational directory only (single tenant). A multi-tenant app accepts users of any tenant, see Providers anyone can sign in with.
  • The redirect URI. Select the Web platform and enter the redirect_uri given to Openid::register, such as http://localhost:8080/.

registration panel

After the registration, the overview page shows the Application (client) ID and the Directory (tenant) ID.

registration complete

Client secret

Open Manage -> Certificates & secrets, click New client secret and copy its Value right away, since Entra only shows it once. GreyCat reads it from the ENTRA_CLIENT_SECRET environment variable below. GreyCat uses the Authorization Code flow, so the ID tokens option under Implicit grant and hybrid flows can stay unchecked.

Token configuration

The scopes openid and profile give the ID token a preferred_username (the user principal name), which is what GreyCat should match Entra users on. To also receive the email claim, open Manage -> Token configuration, click Add optional claim, choose the ID token type and check email. Entra may ask you to grant the matching Microsoft Graph permission.

token_config

The permissions granted to the application are listed under Manage -> API permissions.

api_permissions

Define roles

Entra app roles assigned to a user are sent in the roles claim of the ID token, which role_hook reads. The Value of each app role must match a key of the mapping in the hook. To create one, open Manage -> App roles and click Create app role.

role config

Assign roles

Assign app roles to users from Applications -> Enterprise applications -> <your application>, then Manage -> Users and groups. Use Add user/group to assign a role, or Edit assignment to change one. A GreyCat Identity has a single role, so role_hook keeps the first role of the mapping that the user holds.

assign role

GreyCat configuration

The client id is the Application (client) ID of the overview page. The OpenID Connect metadata document listed under Endpoints is https://login.microsoftonline.com/<tenant id>/v2.0/.well-known/openid-configuration, so the issuer is https://login.microsoftonline.com/<tenant id>/v2.0.

key information

Put the values in the .env file of your project:

ENTRA_TENANT_ID=<Directory (tenant) ID>
ENTRA_CLIENT_ID=<Application (client) ID>
ENTRA_CLIENT_SECRET=<client secret value>

Then register the provider and the role hook:

fn main() {
    var tenant = System::getEnv("ENTRA_TENANT_ID")!!;
    Openid::register("entra", OidcProvider {
        issuer: "https://login.microsoftonline.com/${tenant}/v2.0",
        client_id: System::getEnv("ENTRA_CLIENT_ID")!!,
        client_secret: System::getEnv("ENTRA_CLIENT_SECRET"),
        scopes: ["openid", "email", "profile"],
        redirect_uri: "http://localhost:8080/",
    });
    Openid::set_hook(role_hook);
}

Using Google

[Back to the beginning]

Create a project

This walkthrough assumes a configured Google Cloud account. Create a project in the Google API and services console with the CREATE PROJECT button in the top right corner.

Create project

Name the project (it cannot be renamed later). Attaching it to an organization is optional, and this demo leaves it empty.

project creation

Create a credential

Open the Credentials panel from the left menu, click Create credentials and select OAuth client ID.

try create credential

Google first asks for a consent screen. Click Configure consent screen.

Force customize consent screen

Choose the target users. Internal limits sign-in to the users of your organization. External accepts any Google account holder. This demo has no organization, so it selects External and clicks Create.

users

Fill in the content of the consent page, then click Save and continue.

consent page

Define the scopes. GreyCat needs openid, and the email is how it recognizes Google users. Click Add or remove scopes, check at least openid and .../auth/userinfo.email (and .../auth/userinfo.profile to match the profile scope requested by GreyCat), then click Update.

edit scopes

The selected scopes are listed:

scopes

While the app is in testing, only test users can sign in. Click Add users and add at least your own address.

test users

The test users are listed. Click Save and continue.

added test users

Check the summary and click Back to dashboard.

summary

Create credentials

Back in the Credentials panel, click Create credentials and select OAuth client ID again.

restart credential creation

Select Web application as the application type.

pick application type

Fill in:

  • Application type: Web application
  • Authorized JavaScript origins: the address of GreyCat, such as http://localhost:8080. Only the token-exchange flow needs it.
  • Authorized redirect URIs: the redirect_uri given to Openid::register, with the trailing /, such as http://localhost:8080/. Without the /, Google answers redirect_uri_mismatch.

origins

The dialog then shows the Client ID and the Client secret of the new client. Copy both.

summary

Both stay available from the Credentials panel, under the OAuth client you created.

Client ID

GreyCat configuration

Put the values in the .env file of your project:

GOOGLE_CLIENT_ID=<Client ID>
GOOGLE_CLIENT_SECRET=<Client secret>

Register the provider as in Registering a provider. Google sends no roles, and any Google account can sign in to an External app. Do not turn auto_create_identity on. Either create the GreyCat Identities ahead, named after the Google email addresses (the default resolver matches the verified email):

greycat user add jane.doe@gmail.com user

or set a hook that decides who may sign in, such as domain_hook in Hooks.

Start GreyCat with greycat serve, open http://localhost:8080/ and choose google on the sign-in page. Google then shows its account chooser:

login page