You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@grails.apache.org by "amondel2 (via GitHub)" <gi...@apache.org> on 2026/10/10 16:06:03 UTC
[PR] Grails keycloak [grails-static-website]
amondel2 opened a new pull request, #563:
URL: https://github.com/apache/grails-static-website/pull/563
PR description
## Summary
The version currently on master was a first draft. This PR is a significant
improvement across grammar, explanation, and flow, and substantially reduces
the AI-generated phrasing that carried over from that draft.
## What changed
**Added a Testing chapter** between "Run the Application" and "Do You Need
Help With Grails", covering the role-mapper unit spec and the controller
integration specs, vendored from the grails-keycloak sample. Prose explains
why an offline stand-in client registration is needed and what the suite does
*not* prove.
**Rewrote configureGrails for a first-time reader.** "Understanding the code"
explains how Keycloak and Grails fit together before showing each class, with
per-class "what it does" notes. KeycloakAuthoritiesMapper is registered as a
Spring bean in resources.groovy.
**Three equivalent ways to run Keycloak.** The chapter opens with the Docker
command, then bin/kc.sh on Linux and bin\kc.bat on Windows. Each bootstraps
the same admin account so the administration console login works whichever
path a reader takes.
**Prose overhaul throughout**: assumptions and OS notes moved into Getting
Started instead of interrupting the start commands, the two redundant
configuration summaries at the end of the Keycloak chapter merged into one,
the role-missing checklist moved into Troubleshooting, and rendering defects
fixed (an apostrophe that broke a code span, a missing blank line that
swallowed a heading into a code block).
**Simplified the header snippet's logout form** to a `g:form` with `useToken`,
dropping the manual CSRF token plumbing.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Grails keycloak [grails-static-website]
Posted by "sbglasius (via GitHub) via commits" <co...@grails.apache.org>.
sbglasius commented on code in PR #563:
URL: https://github.com/apache/grails-static-website/pull/563#discussion_r4577769372
##########
guides/grails-keycloak/v8/guide/runningTheApp.adoc:
##########
@@ -1,26 +1,32 @@
-Start Keycloak, export `KEYCLOAK_CLIENT_ID`, `KEYCLOAK_CLIENT_SECRET`, and `KEYCLOAK_ISSUER`, then start Grails from `complete/`:
+After Keycloak is running and the environment variables are set, start the Grails app:
[source,bash]
----
cd complete
-./gradlew bootRun
+./grailsw bootRun
Review Comment:
`bootRun` is a Gradle task, not a Grails CLI command (the Grails equivalent is `run-app`). The Windows line below still says `gradlew.bat bootRun`, and the Testing chapter uses `./gradlew`. Suggest reverting to `./gradlew bootRun` so all platforms and chapters match.
##########
guides/grails-keycloak/v8/snippets/grails-app/views/layouts/_header.gsp:
##########
@@ -22,18 +22,11 @@
${it.firstName} ${it.lastName}
</app:currentUser>
</span>
- <g:set var="csrfToken" value="${request.getAttribute('org.springframework.security.web.csrf.CsrfToken')}"/>
- <g:if test="${csrfToken instanceof java.util.function.Supplier}">
- <g:set var="csrfToken" value="${csrfToken.get()}"/>
- </g:if>
- <form action="${createLink(uri: '/logout')}" method="post" class="logout-form">
- <g:if test="${csrfToken}">
- <g:hiddenField name="${csrfToken.parameterName}" value="${csrfToken.token}"/>
- </g:if>
+ <g:form method="post" url="[uri: '/logout']" useToken="true" class="logout-form">
Review Comment:
This removes the explicit `_csrf` hidden field. The logout form now gets a CSRF field only if `g:form` finds Spring Security's `requestDataValueProcessor` bean, and nothing in the guide or its tests shows that this happens. The chapter this PR deletes stated the opposite (that `useToken` does not satisfy the CSRF filter).
If that bean is missing or overridden, the form posts `/logout` without `_csrf`, `CsrfFilter` returns 403, and users can't log out. Neither integration spec renders the header or POSTs to `/logout`. Please confirm in the rendered HTML that the `_csrf` field is actually emitted, and ideally add a test for it.
Separately, `useToken="true"` is dead weight. Spring's `LogoutFilter` handles `/logout` before any `withForm` could validate the synchronizer token, so the token is just stored in the session every time the header renders and never checked. The prose at configureGrails.adoc:180 and in runningTheApp.adoc makes it sound like it matters.
##########
guides/grails-keycloak/v8/guide/configureGrails.adoc:
##########
@@ -1,31 +1,269 @@
-Add the Spring Security client libraries to `build.gradle`. Grails 8.0.0 manages the Spring Boot 4.1.1 line through `grails-bom`, so these two dependencies do not need their own versions:
+This chapter describes how to configure the Grails application to connect to Keycloak via environment variables.
+
+== Add the OAuth2 Client dependency
+
+Add the Spring Security OAuth2 Client starter to `build.gradle`:
[source,groovy]
+.build.gradle
----
-implementation 'org.springframework.boot:spring-boot-starter-security'
-implementation 'org.springframework.boot:spring-boot-starter-oauth2-client'
+include::../snippets/build.gradle[]
----
-`complete/gradle.properties` sets `grailsVersion=8.0.0`. Keep `initial/gradle.properties` on that same version.
+`spring-boot-starter-security` provides the core Spring Security filter chain, and `spring-boot-starter-oauth2-client` brings in the OpenID Connect client support that Keycloak relies on.
-== application.yml
+== Keycloak configuration
-The datasource stays on embedded H2. The Keycloak registration is the `keycloak` client under Spring Security's OAuth2 client properties. The registration id is the last segment of the login callback, `/login/oauth2/code/keycloak`.
+Set the Keycloak OIDC issuer and client credentials via environment variables:
+
+[source,text]
+----
+export KEYCLOAK_CLIENT_ID=example-client
+export KEYCLOAK_CLIENT_SECRET=change-me
+export KEYCLOAK_ISSUER=http://localhost:8081/realms/example
+----
+
+Then register the Keycloak client in `grails-app/conf/application.yml`:
[source,yaml]
+.grails-app/conf/application.yml
Review Comment:
The caption says `grails-app/conf/application.yml`, but the include is `application-keycloak.yml`. That is a Spring profile file and only loads when the `keycloak` profile is active.
If a reader copies the snippet's filename and runs `bootRun` with no profile, no client registration gets bound and there is no `ClientRegistrationRepository` bean. `SecurityConfig.securityFilterChain` then can't be autowired and the app fails to start. Please either rename the snippet to match the caption, or document how to activate the profile (`SPRING_PROFILES_ACTIVE=keycloak`).
##########
guides/grails-keycloak/v8/guide/configureGrails.adoc:
##########
@@ -1,31 +1,269 @@
-Add the Spring Security client libraries to `build.gradle`. Grails 8.0.0 manages the Spring Boot 4.1.1 line through `grails-bom`, so these two dependencies do not need their own versions:
+This chapter describes how to configure the Grails application to connect to Keycloak via environment variables.
+
+== Add the OAuth2 Client dependency
+
+Add the Spring Security OAuth2 Client starter to `build.gradle`:
[source,groovy]
+.build.gradle
----
-implementation 'org.springframework.boot:spring-boot-starter-security'
-implementation 'org.springframework.boot:spring-boot-starter-oauth2-client'
+include::../snippets/build.gradle[]
----
-`complete/gradle.properties` sets `grailsVersion=8.0.0`. Keep `initial/gradle.properties` on that same version.
+`spring-boot-starter-security` provides the core Spring Security filter chain, and `spring-boot-starter-oauth2-client` brings in the OpenID Connect client support that Keycloak relies on.
-== application.yml
+== Keycloak configuration
-The datasource stays on embedded H2. The Keycloak registration is the `keycloak` client under Spring Security's OAuth2 client properties. The registration id is the last segment of the login callback, `/login/oauth2/code/keycloak`.
+Set the Keycloak OIDC issuer and client credentials via environment variables:
+
+[source,text]
+----
+export KEYCLOAK_CLIENT_ID=example-client
+export KEYCLOAK_CLIENT_SECRET=change-me
+export KEYCLOAK_ISSUER=http://localhost:8081/realms/example
+----
+
+Then register the Keycloak client in `grails-app/conf/application.yml`:
[source,yaml]
+.grails-app/conf/application.yml
+----
+include::../snippets/grails-app/conf/application-keycloak.yml[]
+----
+
+These settings tell Spring Security how to talk to Keycloak:
+
+* `${KEYCLOAK_ISSUER}` tells Spring Security where Keycloak is and where to find its OpenID Connect metadata (including the token endpoint that signs your login).
+* `client-id` and `client-secret` identify your app to Keycloak. They come from the `example-client` you created in the Keycloak chapter.
+* `authorization-grant-type: authorization_code` is the standard, most secure way for a user to log in through their browser.
+* `redirect-uri` is the URL Keycloak sends the user back to after login. It matches the redirect URI you configured in Keycloak (`{baseUrl}` becomes `http://localhost:8080` at runtime).
+* The `scope` list (openid, profile, email) tells Keycloak which user details to include in the token.
+
+Keep client secrets out of source control; use environment variables or a secrets manager.
+
+== Understanding the code
+
+This section explains the key components that wire Keycloak authentication into your Grails application. If you're new to Keycloak or Grails, read this section carefully—each class solves a specific problem in the authentication flow. Each snippet is a complete file; create it at the path shown in the caption, and the pieces will fit together exactly as described.
+
+=== How Keycloak and Grails work together
+
+Before diving into the code, here's what happens when a user logs in:
+
+1. User clicks a protected link in your Grails app and isn't logged in.
+2. The app redirects to Keycloak's login page (on a different server).
+3. User enters their username and password into Keycloak's login form.
+4. Keycloak validates the credentials and issues a security token (JWT) containing the user's identity and roles.
+5. Keycloak redirects back to your Grails app with the token.
Review Comment:
In the authorization-code flow this guide configures, Keycloak redirects back with an authorization code, not the token. Spring exchanges the code for tokens server-side. The deleted chapter described this correctly.
Also, around line 41, the token endpoint does not "sign your login". The signing keys come from `jwks_uri` in the discovery document.
##########
guides/grails-keycloak/v8/guide/keycloakSetup.adoc:
##########
@@ -1,4 +1,10 @@
-Run Keycloak on port 8081 so it does not collide with the Grails application on port 8080.
+This chapter covers the Keycloak configuration used by the example application: running Keycloak with `start-dev`, the realm and client, roles, the client role mapper, and test users.
+
+Keycloak `start-dev` keeps its own embedded database. No external database setup is required.
+
+== Start Keycloak
+
+If you have Docker, you can start Keycloak with the command below instead of installing it:
Review Comment:
This change makes the Docker command the main way to start Keycloak, but that command (unchanged below) runs `start-dev` with `--rm` and no volume. Keycloak's embedded H2 store lives inside the container, so stopping it throws away the realm, client, roles, mapper, users, and client secret. After a restart, login fails with "Realm does not exist" and the exported `KEYCLOAK_CLIENT_SECRET` no longer matches anything. Consider adding a named volume (`-v grails-keycloak-data:/opt/keycloak/data`) or a warning.
##########
guides/grails-keycloak/v8/guide/configureGrails.adoc:
##########
@@ -1,31 +1,269 @@
-Add the Spring Security client libraries to `build.gradle`. Grails 8.0.0 manages the Spring Boot 4.1.1 line through `grails-bom`, so these two dependencies do not need their own versions:
+This chapter describes how to configure the Grails application to connect to Keycloak via environment variables.
+
+== Add the OAuth2 Client dependency
+
+Add the Spring Security OAuth2 Client starter to `build.gradle`:
[source,groovy]
+.build.gradle
----
-implementation 'org.springframework.boot:spring-boot-starter-security'
-implementation 'org.springframework.boot:spring-boot-starter-oauth2-client'
+include::../snippets/build.gradle[]
----
-`complete/gradle.properties` sets `grailsVersion=8.0.0`. Keep `initial/gradle.properties` on that same version.
+`spring-boot-starter-security` provides the core Spring Security filter chain, and `spring-boot-starter-oauth2-client` brings in the OpenID Connect client support that Keycloak relies on.
-== application.yml
+== Keycloak configuration
-The datasource stays on embedded H2. The Keycloak registration is the `keycloak` client under Spring Security's OAuth2 client properties. The registration id is the last segment of the login callback, `/login/oauth2/code/keycloak`.
+Set the Keycloak OIDC issuer and client credentials via environment variables:
+
+[source,text]
+----
+export KEYCLOAK_CLIENT_ID=example-client
+export KEYCLOAK_CLIENT_SECRET=change-me
+export KEYCLOAK_ISSUER=http://localhost:8081/realms/example
+----
+
+Then register the Keycloak client in `grails-app/conf/application.yml`:
[source,yaml]
+.grails-app/conf/application.yml
+----
+include::../snippets/grails-app/conf/application-keycloak.yml[]
+----
+
+These settings tell Spring Security how to talk to Keycloak:
+
+* `${KEYCLOAK_ISSUER}` tells Spring Security where Keycloak is and where to find its OpenID Connect metadata (including the token endpoint that signs your login).
+* `client-id` and `client-secret` identify your app to Keycloak. They come from the `example-client` you created in the Keycloak chapter.
+* `authorization-grant-type: authorization_code` is the standard, most secure way for a user to log in through their browser.
+* `redirect-uri` is the URL Keycloak sends the user back to after login. It matches the redirect URI you configured in Keycloak (`{baseUrl}` becomes `http://localhost:8080` at runtime).
+* The `scope` list (openid, profile, email) tells Keycloak which user details to include in the token.
+
+Keep client secrets out of source control; use environment variables or a secrets manager.
+
+== Understanding the code
+
+This section explains the key components that wire Keycloak authentication into your Grails application. If you're new to Keycloak or Grails, read this section carefully—each class solves a specific problem in the authentication flow. Each snippet is a complete file; create it at the path shown in the caption, and the pieces will fit together exactly as described.
+
+=== How Keycloak and Grails work together
+
+Before diving into the code, here's what happens when a user logs in:
+
+1. User clicks a protected link in your Grails app and isn't logged in.
+2. The app redirects to Keycloak's login page (on a different server).
+3. User enters their username and password into Keycloak's login form.
+4. Keycloak validates the credentials and issues a security token (JWT) containing the user's identity and roles.
+5. Keycloak redirects back to your Grails app with the token.
+6. The Grails app receives the token and needs to extract the user's information and roles from it.
+7. Spring Security (a framework that Grails uses) stores this info so pages and controllers can check "is this user logged in?" and "does this user have the ADMIN role?"
+
+The classes below handle steps 6 and 7.
+
+=== SecurityConfig: The gatekeeper
+
+SecurityConfig tells Spring Security which URLs anyone can access without logging in, and which ones require login. It also configures how Keycloak tokens are processed.
+
+[source,groovy]
+.snippets/src/main/groovy/com/grails/example/SecurityConfig.groovy
----
-include::../snippets/grails-app/conf/application.yml[]
+include::../snippets/src/main/groovy/com/grails/example/SecurityConfig.groovy[]
----
-`KEYCLOAK_ISSUER` is the realm issuer, `http://localhost:8081/realms/example`, not the Keycloak root URL.
+**What it does:**
+
+* `@Configuration` marks this as a Spring configuration class—Spring reads it on startup and applies these rules.
+* `.permitAll()` on `/`, `/assets/**`, etc. means anyone can visit these URLs without logging in (public pages).
+* `.anyRequest().authenticated()` means **every other URL requires the user to be logged in**. If they're not, they're sent to Keycloak.
+* `.oauth2Login()` tells Spring Security to accept logins via OAuth2/OIDC (the protocol Keycloak uses). This is the "bridge" that lets Keycloak handle passwords.
+* `userAuthoritiesMapper(keycloakAuthoritiesMapper)` is the key line: after the user logs in and Keycloak sends back their info, this tells Spring Security to run the `KeycloakAuthoritiesMapper` to extract the user's roles.
+* `.logout()` configures logout to tell Keycloak the user is leaving, not just delete the local session.
-== Register the role mapper
+=== KeycloakAuthoritiesMapper: Translating roles into permissions
-`KeycloakAuthoritiesMapper` is not a Spring stereotype. Register it in `grails-app/conf/spring/resources.groovy` so `SecurityConfig` can inject it:
+When Keycloak sends back the user's info, it includes a JWT token with a claims section. That claims section contains roles, but they're formatted in a way Keycloak understands—not in a way Spring Security understands. This class translates them.
[source,groovy]
+.snippets/src/main/groovy/com/grails/example/KeycloakAuthoritiesMapper.groovy
+----
+include::../snippets/src/main/groovy/com/grails/example/KeycloakAuthoritiesMapper.groovy[]
+----
+
+**What it does:**
+
+The Keycloak JWT token contains a section called `resource_access.<clientId>.roles`. For example:
+
+```json
+{
+ "resource_access": {
+ "my-app": {
Review Comment:
The example uses client id `my-app`, as does step 4 of "Putting it all together" (`resource_access.my-app.roles`). The guide's client is `example-client`, and the mapper only looks up the configured client id, so readers who compare this against their Evaluate output will be misled. Suggest using `example-client` throughout.
##########
guides/grails-keycloak/v8/guide/keycloakSetup.adoc:
##########
@@ -10,134 +16,379 @@ docker run --rm --name grails-keycloak \
start-dev
----
-Open http://localhost:8081[http://localhost:8081] and sign in as `admin` / `admin`. `start-dev` reads the browser's host, so the issuer for this guide is `http://localhost:8081/realms/example`.
+From the Keycloak installation directory, start Keycloak in development mode:
+
+[source,bash]
+----
+bin/kc.sh start-dev --http-port=8081 \
+ --bootstrap-admin-username admin \
+ --bootstrap-admin-password admin
+----
+
+On Windows:
-== Realm and client
+[source,bash]
+----
+bin\kc.bat start-dev --http-port=8081 --bootstrap-admin-username admin --bootstrap-admin-password admin
+----
-Create a realm named `example`.
+`start-dev` uses an embedded H2 database. No database configuration is needed.
-In that realm, create an OpenID Connect client:
+== Access the Keycloak administration console
-[options="header"]
-|===
-|Setting |Value
+Once Keycloak is running, open `http://localhost:8081` and log into the administration console. All three start commands in this chapter create the same administrator account: `admin` / `admin`.
-|Client type
-|OpenID Connect
+If you are accessing Keycloak from another machine, replace `localhost` with the hostname or address where Keycloak is running.
-|Client ID
-|`example-client`
+== Create the example realm
-|Client authentication
-|On
+From the Keycloak Administration Console, create a new realm:
-|Standard flow
-|On
+```text
+Realm name:
+example
+```
-|Valid redirect URIs
-|`http://localhost:8080/login/oauth2/code/keycloak`
+The OpenID Connect issuer for the realm is:
-|Valid post logout redirect URIs
-|`http://localhost:8080`
+```text
+http://localhost:8081/realms/example
+```
-|Web origins
-|`http://localhost:8080`
-|===
+This value becomes the Grails application's `KEYCLOAK_ISSUER` environment variable.
-The redirect URI is the Spring Security login callback. The post-logout URI is `{baseUrl}` from the application, which is `http://localhost:8080` when Grails listens on that port. Keycloak 18 and later rejects a logout redirect that is not registered. In the Keycloak 26 client settings this field is under *Logout settings*.
+== Create the OpenID Connect client
-Copy the client secret from *Clients -> example-client -> Credentials*. The application reads it from `KEYCLOAK_CLIENT_SECRET`. Do not commit the secret.
+Navigate to **Clients → Create client** and create an OpenID Connect client:
-== Client roles
+```text
+Client type:
+OpenID Connect
-Create `USER` and `ADMIN` under *Clients -> example-client -> Roles*. The mapper in this guide reads `resource_access.example-client.roles` from the ID token. Roles created under *Realm roles* are not in that claim, so a user can sign in and still fail every `@PreAuthorize` check.
+Client ID:
+example-client
+```
-Open `ADMIN` and add `USER` as an associated role so `ADMIN` is a composite role. A user who is assigned only `ADMIN` then receives both `ADMIN` and `USER` in the client-role claim. The Account page requires `USER`, and the Admin page requires `ADMIN`, so an administrator can open both.
+The `Client ID` becomes the Grails application's `KEYCLOAK_CLIENT_ID` environment variable.
-== Put the client roles on the ID token
+=== Enable client authentication
-Open *Clients -> example-client -> Client scopes -> dedicated scope* and add a mapper of type *User Client Role*.
+Enable client authentication for the client. Keycloak generates a client secret. That secret becomes the Grails application's `KEYCLOAK_CLIENT_SECRET` environment variable.
-[options="header"]
-|===
-|Setting |Value
+Do not commit the client secret to Git.
+
+=== Configure redirect URIs
+
+For the example application running locally on port `8080`, configure the redirect URI:
+
+```text
+http://localhost:8080/login/oauth2/code/keycloak
+```
+
+This is the OAuth2 login callback used by the Grails application. If you run the application on a different URL, change the redirect URI accordingly.
+
+=== Configure web origins
+
+For local development, configure:
+
+```text
+http://localhost:8080
+```
+
+as the web origin. Do not use unrestricted origins unless they are specifically required.
+
+== Create the client roles
+
+This example uses client roles rather than realm roles.
+
+=== USER role
+
+Navigate to **Clients → example-client → Roles** and create:
+
+```text
+USER
+```
+
+Do not create this under **Realm roles**. The application uses `USER` for normal authenticated users:
+
+[source,groovy]
+----
+@PreAuthorize("hasRole('ROLE_USER')")
Review Comment:
This shows `hasRole('ROLE_USER')` (and `hasRole('ROLE_ADMIN')` further down, plus once in configureGrails). The controllers use `hasRole('USER')` and `hasRole('ADMIN')`. Both work for `hasRole`, but the guide now contradicts the code it includes. Readers who carry the prefix over to `<app:hasRole role="ROLE_ADMIN">` would get `ROLE_ROLE_ADMIN`. Suggest the unprefixed form, which matches the controllers.
##########
guides/grails-keycloak/v8/snippets/src/integration-test/groovy/com/grails/example/AccountControllerIntegrationSpec.groovy:
##########
@@ -0,0 +1,68 @@
+package com.grails.example
+
+import grails.testing.mixin.integration.Integration
+import org.springframework.beans.factory.annotation.Autowired
+import org.springframework.context.annotation.Import
+import org.springframework.security.access.AccessDeniedException
+import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException
+import org.springframework.security.core.authority.SimpleGrantedAuthority
+import org.springframework.test.annotation.Rollback
+import spock.lang.Specification
+
+/**
+ * Proves the account pages sit behind the ROLE_USER gate.
+ *
+ * The controller is autowired so the call goes through the Spring proxy,
+ * which is where the @PreAuthorize interceptor fires. Each feature first
+ * places a token carrying the desired authorities in the security context,
+ * standing in for what Keycloak yields after login.
+ */
+@Integration
+@Rollback
+@Import(TestOAuth2ClientConfiguration)
+class AccountControllerIntegrationSpec extends Specification implements SecuredRequestSupport {
+
+ @Autowired
+ AccountController accountController
+
+ def cleanup() {
+ clearAuthContext()
+ }
+
+ void "index resolves the account view for an authenticated user with ROLE_USER"() {
+ given: 'a request to /account and a mocked token carrying ROLE_USER'
+ mockKeycloakUser()
+ bindRequest('/account')
+
+ when: 'the secured index action runs'
+ accountController.index()
+
+ then: 'the account/index.gsp view resolves with status 200'
+ accountController.response.status == 200
Review Comment:
`MockHttpServletResponse` starts at status 200 and `render(view:)` never changes it, so this assertion can't fail (the same applies in `AdminControllerIntegrationSpec`). The view-name check is the meaningful assertion here.
`@Rollback` is also noise, since these specs never touch a datasource.
testing.adoc says these specs prove the gate "on the action itself", but they call the bean directly and bypass the filter chain and the URL rules in `SecurityConfig`. Adding `/account` to `permitAll` would not fail them. Worth saying that explicitly in the "What these tests do not prove" section.
##########
guides/grails-keycloak/v8/guide/keycloakSetup.adoc:
##########
@@ -10,134 +16,379 @@ docker run --rm --name grails-keycloak \
start-dev
----
-Open http://localhost:8081[http://localhost:8081] and sign in as `admin` / `admin`. `start-dev` reads the browser's host, so the issuer for this guide is `http://localhost:8081/realms/example`.
+From the Keycloak installation directory, start Keycloak in development mode:
+
+[source,bash]
+----
+bin/kc.sh start-dev --http-port=8081 \
+ --bootstrap-admin-username admin \
+ --bootstrap-admin-password admin
+----
+
+On Windows:
-== Realm and client
+[source,bash]
+----
+bin\kc.bat start-dev --http-port=8081 --bootstrap-admin-username admin --bootstrap-admin-password admin
+----
-Create a realm named `example`.
+`start-dev` uses an embedded H2 database. No database configuration is needed.
-In that realm, create an OpenID Connect client:
+== Access the Keycloak administration console
-[options="header"]
-|===
-|Setting |Value
+Once Keycloak is running, open `http://localhost:8081` and log into the administration console. All three start commands in this chapter create the same administrator account: `admin` / `admin`.
-|Client type
-|OpenID Connect
+If you are accessing Keycloak from another machine, replace `localhost` with the hostname or address where Keycloak is running.
-|Client ID
-|`example-client`
+== Create the example realm
-|Client authentication
-|On
+From the Keycloak Administration Console, create a new realm:
-|Standard flow
-|On
+```text
+Realm name:
+example
+```
-|Valid redirect URIs
-|`http://localhost:8080/login/oauth2/code/keycloak`
+The OpenID Connect issuer for the realm is:
-|Valid post logout redirect URIs
-|`http://localhost:8080`
+```text
+http://localhost:8081/realms/example
+```
-|Web origins
-|`http://localhost:8080`
-|===
+This value becomes the Grails application's `KEYCLOAK_ISSUER` environment variable.
-The redirect URI is the Spring Security login callback. The post-logout URI is `{baseUrl}` from the application, which is `http://localhost:8080` when Grails listens on that port. Keycloak 18 and later rejects a logout redirect that is not registered. In the Keycloak 26 client settings this field is under *Logout settings*.
+== Create the OpenID Connect client
-Copy the client secret from *Clients -> example-client -> Credentials*. The application reads it from `KEYCLOAK_CLIENT_SECRET`. Do not commit the secret.
+Navigate to **Clients → Create client** and create an OpenID Connect client:
-== Client roles
+```text
+Client type:
+OpenID Connect
-Create `USER` and `ADMIN` under *Clients -> example-client -> Roles*. The mapper in this guide reads `resource_access.example-client.roles` from the ID token. Roles created under *Realm roles* are not in that claim, so a user can sign in and still fail every `@PreAuthorize` check.
+Client ID:
+example-client
+```
-Open `ADMIN` and add `USER` as an associated role so `ADMIN` is a composite role. A user who is assigned only `ADMIN` then receives both `ADMIN` and `USER` in the client-role claim. The Account page requires `USER`, and the Admin page requires `ADMIN`, so an administrator can open both.
+The `Client ID` becomes the Grails application's `KEYCLOAK_CLIENT_ID` environment variable.
-== Put the client roles on the ID token
+=== Enable client authentication
-Open *Clients -> example-client -> Client scopes -> dedicated scope* and add a mapper of type *User Client Role*.
+Enable client authentication for the client. Keycloak generates a client secret. That secret becomes the Grails application's `KEYCLOAK_CLIENT_SECRET` environment variable.
-[options="header"]
-|===
-|Setting |Value
+Do not commit the client secret to Git.
+
+=== Configure redirect URIs
+
+For the example application running locally on port `8080`, configure the redirect URI:
+
+```text
+http://localhost:8080/login/oauth2/code/keycloak
+```
+
+This is the OAuth2 login callback used by the Grails application. If you run the application on a different URL, change the redirect URI accordingly.
+
+=== Configure web origins
+
+For local development, configure:
+
+```text
+http://localhost:8080
+```
+
+as the web origin. Do not use unrestricted origins unless they are specifically required.
+
+== Create the client roles
+
+This example uses client roles rather than realm roles.
+
+=== USER role
+
+Navigate to **Clients → example-client → Roles** and create:
+
+```text
+USER
+```
+
+Do not create this under **Realm roles**. The application uses `USER` for normal authenticated users:
+
+[source,groovy]
+----
+@PreAuthorize("hasRole('ROLE_USER')")
+----
+
+=== ADMIN role
+
+Under **Clients → example-client → Roles**, create:
+
+```text
+ADMIN
+```
+
+The client now contains `USER` and `ADMIN`. The application protects administrator-only functionality with:
+
+[source,groovy]
+----
+@PreAuthorize("hasRole('ROLE_ADMIN')")
+----
+
+=== Make ADMIN inherit USER
+
+Keycloak supports composite roles. Configure `ADMIN` as a composite role containing `USER`.
+
+Navigate to **Clients → example-client → Roles → ADMIN** and add `USER` as an associated/composite role.
+
+The resulting structure is:
+
+```text
+example-client
+│
+├── USER
+│
+└── ADMIN
+ └── USER
+```
+
+A user assigned `USER` has the effective roles:
+
+```text
+USER
+```
+
+A user assigned `ADMIN` has the effective roles:
+
+```text
+ADMIN
+USER
+```
+
+The administrator does not need `USER` assigned separately. This lets the application secure ordinary functionality with `ROLE_USER` while administrator-only functionality requires `ROLE_ADMIN`.
+
+== Create test users
+
+=== test-user
+
+Navigate to **Users → Add user** and create:
+
+```text
+Username:
+test-user
+
+Email:
+test-user@example.com
+```
-|Name
-|`example-client-roles`
+Set a password under **Credentials**.
-|Client ID
-|`example-client`
+Open the user, navigate to **Role mapping**, select the `example-client` client roles, and assign:
-|Client Role prefix
-|leave blank
+```text
+USER
+```
-|Multivalued
-|On
+The user should have:
-|Token Claim Name
-|`resource_access.example-client.roles`
+```text
+Direct role:
+USER
-|Claim JSON Type
-|String
+Effective roles:
+USER
+```
-|Add to ID token
-|On
+=== test-admin
-|Add to access token
-|On
+Create another user:
-|Add to lightweight access token
-|Off
+```text
+Username:
+test-admin
-|Add to userinfo
-|On
+Email:
+test-admin@example.com
+```
-|Add to token introspection
-|On
+Assign only `ADMIN`. Do not separately assign `USER`. Because `ADMIN` contains `USER`, the effective roles should be:
+
+```text
+Direct role:
+ADMIN
+
+Effective roles:
+ADMIN
+USER
+```
+
+== Add the client role mapper
+
+Creating the roles is not enough. The client roles must also be included in the OpenID Connect tokens consumed by the Grails application.
+
+Navigate to **Clients → example-client → Client scopes → Dedicated scopes** and add a mapper for the client roles, configured for the `example-client` client.
+
+=== Configure the mapper
+
+Configure the mapper with the following settings:
+
+|===
+| Setting | Value
+
+| Add to ID token
+| On
+
+| Add to access token
+| On
+
+| Add to lightweight access token
+| Off
+
+| Add to userinfo
+| On
+
+| Add to token introspection
+| On
|===
-Token Claim Name is required and has no default. That value is the only claim `KeycloakAuthoritiesMapper` reads. Leave Client Role prefix blank so the token contains `USER` and `ADMIN`. The Grails mapper adds `ROLE_`.
+The final configuration is:
-Check the result before starting Grails. Open *Client scopes -> Evaluate*, choose the test user, and generate an ID token. A user with the `USER` client role should show:
+```text
+Add to ID token: On
+Add to access token: On
+Add to lightweight access token: Off
+Add to userinfo: On
+Add to token introspection: On
+```
+
+=== Verify the token with Evaluate
+
+Before troubleshooting the Grails application, verify that Keycloak puts the roles into the token.
+
+Navigate to **Clients → example-client → Client scopes → Evaluate** and select `test-user`.
+
+The Evaluate screen shows the token Keycloak would issue for that user. The `test-user` should show the `USER` client role:
+
+```text
+USER
+```
+
+Select `test-admin` and evaluate again. Because `ADMIN` contains `USER`, the `test-admin` should show both roles:
+
+```text
+ADMIN
+USER
+```
+
+The client roles are typically represented in the token under `resource_access`. For example:
[source,json]
----
{
"resource_access": {
"example-client": {
- "roles": ["USER"]
+ "roles": [
+ "USER"
+ ]
}
}
}
----
-An `ADMIN` user should show both `ADMIN` and `USER` in that same `roles` array.
+An administrator has something similar with both roles:
-== Users
+[source,json]
+----
+{
+ "resource_access": {
+ "example-client": {
+ "roles": [
+ "ADMIN",
+ "USER"
+ ]
+ }
+ }
+}
+----
-Create two users in the `example` realm. Set a non-temporary password on each.
+The exact token output varies by Keycloak version and configuration.
-Assign client roles from *Role mapping -> Assign role*, with the filter set to clients:
+TIP: After changing roles or mapper settings, log out and log back in so that a new token is issued.
-* One user gets `example-client` / `USER` only.
-* The other user gets `example-client` / `ADMIN` only. Composite membership supplies `USER`.
+== Troubleshooting
-== Environment variables
+=== Keycloak does not start
-The Grails application reads three variables. There is no database variable.
+Check the Keycloak logs for errors. Common causes include:
-[source,bash]
-----
-export KEYCLOAK_CLIENT_ID=example-client
-export KEYCLOAK_CLIENT_SECRET=paste-the-client-secret
-export KEYCLOAK_ISSUER=http://localhost:8081/realms/example
-----
+* Port 8081 is already in use
+* Java is not installed or not on the PATH
+* The Keycloak installation is incomplete
-On PowerShell:
+=== Roles are missing from the application
-[source,powershell]
-----
-$env:KEYCLOAK_CLIENT_ID = "example-client"
-$env:KEYCLOAK_CLIENT_SECRET = "paste-the-client-secret"
-$env:KEYCLOAK_ISSUER = "http://localhost:8081/realms/example"
-----
+Start with Keycloak rather than Grails. Use **Clients → example-client → Client scopes → Evaluate** to inspect the token for the affected user.
+
+If the roles are missing from Evaluate, the problem is in Keycloak. Check:
+
+* The roles are client roles.
+* The roles belong to `example-client`.
+* The user has the expected role.
+* `ADMIN` contains `USER`.
+* The client role mapper exists and is configured for `example-client`.
+* Add to ID token, access token, userinfo, and token introspection are On; lightweight access token is Off.
+
+If the roles appear correctly in Evaluate but the Grails application does not recognize them, the problem is likely in the application authority mapping (see the snippets chapter).
Review Comment:
The guide has no "snippets chapter". `understandingTheCode` is deleted in this PR and the mapper explanation now lives in "Configure the Grails Application". Please point there instead.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org