Skip to content

Commit

Permalink
Documenting how to test OIDC with DevServices and minor updates to qu…
Browse files Browse the repository at this point in the history
…arkus-test-keycloak-server
  • Loading branch information
sberyozkin committed Aug 27, 2021
1 parent 3afc800 commit c2a3ab0
Show file tree
Hide file tree
Showing 7 changed files with 146 additions and 25 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -582,7 +582,7 @@ It applies to ID tokens but also to access tokens in a JWT format if the `web-ap
Please see link:security-openid-connect-client#token-propagation[Token Propagation] section about the Authorization Code Flow access token propagation to the downstream services.

[[oidc-provider-client-authentication]]
=== Oidc Provider Client Authentication
== Oidc Provider Client Authentication

`quarkus.oidc.runtime.OidcProviderClient` is used when a remote request to an OpenId Connect Provider has to be done. It has to authenticate to the OpenId Connect Provider when the authorization code has to be exchanged for the ID, access and refresh tokens, when the ID and access tokens have to be refreshed or introspected.

Expand Down Expand Up @@ -784,10 +784,46 @@ Additionally, `OidcWiremockTestResource` set token issuer and audience to `https

`OidcWiremockTestResource` can be used to emulate all OpenId Connect providers.

[[integration-testing-keycloak-devservices]]
=== Dev Services for Keycloak

Using link:security-openid-connect-dev-services[Dev Services for Keycloak] is recommended for the integration testing against Keycloak.
`Dev Services for Keycloak` will launch and initialize a test container: it will create a `quarkus` realm, a `quarkus-app` client (`secret` secret) and add `alice` (`admin` and `user` roles) and `bob` (`user` role) users, where all of these properties can be customized.

First prepare `application.properties`. You can start with a completely empty `application.properties` as `Dev Services for Keycloak` will register `quarkus.oidc.auth-server-url` pointing to the running test container as well as `quarkus.oidc.client-id=quarkus-app` and `quarkus.oidc.credentials.secret=secret`.

But if you already have all the required `quarkus-oidc` properties configured then you only need to associate `quarkus.oidc.auth-server-url` with the `prod` profile for `Dev Services for Keycloak`to start a container, for example:

[source,properties]
----
%prod.quarkus.oidc.auth-server-url=http://localhost:8180/auth/realms/quarkus
----

If a custom realm file has to be imported into Keycloak before running the tests then you can configure `Dev Services for Keycloak` as follows:

[source,properties]
----
%prod.quarkus.oidc.auth-server-url=http://localhost:8180/auth/realms/quarkus
quarkus.keycloak.devservices.realm-path=quarkus-realm.json
----

Finally write a test code the same way as it is described in the <<integration-testing-wiremock, Wiremock>> section above.
The only difference is that `@QuarkusTestResource` is no longer needed:

[source, java]
----
@QuarkusTest
public class CodeFlowAuthorizationTest {
}
----

[[integration-testing-keycloak]]
=== Keycloak
=== KeycloakTestResourceLifecycleManager

If you work with Keycloak then you can test against a live Keycloak instance by adding the following dependency:
If you need to do the integration testing against Keycloak then you are encouraged to do it with <<integration-testing-keycloak-devservices,Dev Services For Keycloak>>.
Use `KeycloakTestResourceLifecycleManager` for your tests only if there is a good reason not to use `Dev Services for Keycloak`.

Start with adding the following dependency:

[source,xml]
----
Expand All @@ -798,7 +834,9 @@ If you work with Keycloak then you can test against a live Keycloak instance by
</dependency>
----

and configure `maven.surefire.plugin` as follows:
which provides `io.quarkus.test.keycloak.server.KeycloakTestResourceLifecycleManager` - an implementaion of `io.quarkus.test.common.QuarkusTestResourceLifecycleManager` which starts a Keycloak container.

And configure `maven.surefire.plugin` as follows:

[source,xml]
----
Expand Down Expand Up @@ -909,5 +947,5 @@ include::{generated-dir}/config/quarkus-oidc.adoc[opts=optional]
* https://openid.net/connect/[OpenID Connect]
* https://tools.ietf.org/html/rfc7519[JSON Web Token]
* link:security-openid-connect-client[Quarkus - Using OpenID Connect and OAuth2 Client and Filters to manage access tokens]
* link:security-openid-connect-dev-services[Dev Services for OpenId Connect]
* link:security-openid-connect-dev-services[Dev Services for Keycloak]
* link:security[Quarkus Security]
100 changes: 95 additions & 5 deletions docs/src/main/asciidoc/security-openid-connect.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -508,7 +508,7 @@ Note it is also recommended to use `quarkus.oidc.token.audience` property to ver
Please see link:security-openid-connect-client#token-propagation[Token Propagation] section about the Bearer access token propagation to the downstream services.

[[oidc-provider-authentication]]
=== Oidc Provider Client Authentication
== Oidc Provider Client Authentication

`quarkus.oidc.runtime.OidcProviderClient` is used when a remote request to an OpenId Connect Provider has to be done. If the bearer token has to be introspected then `OidcProviderClient` has to authenticate to the OpenId Connect Provider. Please see link:security-openid-connect-web-authentication#oidc-provider-client-authentication[OidcProviderClient Authentication] for more information about all the supported authentication options.

Expand Down Expand Up @@ -602,10 +602,98 @@ public class BearerTokenAuthorizationTest {
Testing your `quarkus-oidc` `service` application with `OidcWiremockTestResource` provides the best coverage as even the communication channel is tested against the Wiremock HTTP stubs.
`OidcWiremockTestResource` will be enhanced going forward to support more complex Bearer token test scenarios.

[[integration-testing-keycloak-devservices]]
=== Dev Services for Keycloak

Using link:security-openid-connect-dev-services[Dev Services for Keycloak] is recommended for the integration testing against Keycloak.
`Dev Services for Keycloak` will launch and initialize a test container: it will create a `quarkus` realm, a `quarkus-app` client (`secret` secret) and add `alice` (`admin` and `user` roles) and `bob` (`user` role) users, where all of these properties can be customized.

First you need to add the following dependency:

[source,xml]
----
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-test-keycloak-server</artifactId>
<scope>test</scope>
</dependency>
----

which provides a utility class `io.quarkus.test.keycloak.client.KeycloakTestClient` you can use in tests for acquiring the access tokens.

Next prepare `application.properties`. You can start with a completely empty `application.properties` as `Dev Services for Keycloak` will register `quarkus.oidc.auth-server-url` pointing to the running test container as well as `quarkus.oidc.client-id=quarkus-app` and `quarkus.oidc.credentials.secret=secret`.

But if you already have all the required `quarkus-oidc` properties configured then you only need to associate `quarkus.oidc.auth-server-url` with the `prod` profile for `Dev Services for Keycloak`to start a container, for example:

[source,properties]
----
%prod.quarkus.oidc.auth-server-url=http://localhost:8180/auth/realms/quarkus
----

If a custom realm file has to be imported into Keycloak before running the tests then you can configure `Dev Services for Keycloak` as follows:

[source,properties]
----
%prod.quarkus.oidc.auth-server-url=http://localhost:8180/auth/realms/quarkus
quarkus.keycloak.devservices.realm-path=quarkus-realm.json
----

Finally write a test code which will work in the JVM mode:

[source,java]
----
package org.acme.security.openid.connect;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.keycloak.client.KeycloakTestClient;
import io.restassured.RestAssured;
import org.junit.jupiter.api.Test;
@QuarkusTest
public class BearerTokenAuthenticationTest {
KeycloakTestClient keycloakClient = new KeycloakTestClient();
@Test
public void testAdminAccess() {
RestAssured.given().auth().oauth2(getAccessToken("alice"))
.when().get("/api/admin")
.then()
.statusCode(200);
RestAssured.given().auth().oauth2(getAccessToken("bob"))
.when().get("/api/admin")
.then()
.statusCode(403);
}
protected String getAccessToken(String userName) {
return keycloakClient.getAccessToken(userName);
}
}
----

and the native mode:

[source,java]
----
package org.acme.security.openid.connect;
import io.quarkus.test.junit.QuarkusIntegrationTest;
@QuarkusIntegrationTest
public class NativeBearerTokenAuthenticationIT extends BearerTokenAuthenticationTest {
}
----

Please see link:security-openid-connect-dev-services[Dev Services for Keycloak] for more information about the way it is initialized and configured.

[[integration-testing-keycloak]]
=== Keycloak
=== KeycloakTestResourceLifecycleManager

If you need to do the integration testing against Keycloak then you are encouraged to do it with <<integration-testing-keycloak-devservices,Dev Services For Keycloak>>.
Use `KeycloakTestResourceLifecycleManager` for your tests only if there is a good reason not to use `Dev Services for Keycloak`.

If you work with Keycloak then you can test against a live Keycloak instance by adding the following dependency:
Start with adding the following dependency:

[source,xml]
----
Expand All @@ -616,7 +704,9 @@ If you work with Keycloak then you can test against a live Keycloak instance by
</dependency>
----

and configure `maven.surefire.plugin` as follows:
which provides `io.quarkus.test.keycloak.server.KeycloakTestResourceLifecycleManager` - an implementaion of `io.quarkus.test.common.QuarkusTestResourceLifecycleManager` which starts a Keycloak container.

And configure `maven.surefire.plugin` as follows:

[source,xml]
----
Expand Down Expand Up @@ -917,5 +1007,5 @@ Note Quarkus `web-app` applications always require `quarkus.oidc.client-id` prop
* https://openid.net/connect/[OpenID Connect]
* https://tools.ietf.org/html/rfc7519[JSON Web Token]
* link:security-openid-connect-client[Quarkus - Using OpenID Connect and OAuth2 Client and Filters to manage access tokens]
* link:security-openid-connect-dev-services[Dev Services for OpenId Connect]
* link:security-openid-connect-dev-services[Dev Services for Keycloak]
* link:security[Quarkus Security]
Original file line number Diff line number Diff line change
Expand Up @@ -40,15 +40,15 @@ public void testAccessAndRefreshTokenInjectionDevMode() throws IOException, Inte

try {
webClient.getPage("http://localhost:8080/protected");
fail("Exception is expected because auth-server-url is not available and the authentication can not be completed");
fail("Exception is expected because by default the bearer token is required");
} catch (FailingHttpStatusCodeException ex) {
// Reported by Quarkus
assertEquals(500, ex.getStatusCode());
assertEquals(401, ex.getStatusCode());
}

// Enable auth-server-url
// Enable 'web-app' application type
test.modifyResourceFile("application.properties",
s -> s.replace("#quarkus.oidc.auth-server-url", "quarkus.oidc.auth-server-url"));
s -> s.replace("#quarkus.oidc.application-type=web-app", "quarkus.oidc.application-type=web-app"));

HtmlPage page = webClient.getPage("http://localhost:8080/protected");

Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
#quarkus.oidc.auth-server-url=${keycloak.url}/realms/quarkus
quarkus.oidc.client-id=quarkus-web-app
quarkus.oidc.credentials.secret=secret
quarkus.oidc.application-type=web-app

quarkus.keycloak.devservices.enabled=false
#quarkus.oidc.application-type=web-app

quarkus.log.category."com.gargoylesoftware.htmlunit.javascript.host.css.CSSStyleSheet".level=FATAL

Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

import io.quarkus.test.common.QuarkusTestResource;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.keycloak.server.KeycloakTestClient;
import io.quarkus.test.keycloak.client.KeycloakTestClient;
import io.restassured.RestAssured;

@QuarkusTest
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
package io.quarkus.test.keycloak.server;
package io.quarkus.test.keycloak.client;

import org.eclipse.microprofile.config.ConfigProvider;
import org.keycloak.representations.AccessTokenResponse;

import io.quarkus.runtime.configuration.ConfigurationException;
import io.quarkus.test.common.DevServicesContext;
import io.quarkus.test.junit.QuarkusIntegrationTest;
import io.restassured.RestAssured;

public class KeycloakTestClient implements DevServicesContext.ContextAware {
Expand All @@ -24,10 +23,6 @@ public KeycloakTestClient() {

}

public KeycloakTestClient(QuarkusIntegrationTest.Context testContext) {
this.testContext = testContext;
}

public String getAccessToken(String userName) {
return getAccessToken(userName, getClientId());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ public Map<String, String> start() {

Map<String, String> conf = new HashMap<>();
conf.put("keycloak.url", KEYCLOAK_SERVER_URL);
conf.put("quarkus.oidc.auth-server-url", KEYCLOAK_SERVER_URL + "/realms/" + KEYCLOAK_REALM);

return conf;
}
Expand Down

0 comments on commit c2a3ab0

Please sign in to comment.