Skip to content

Commit

Permalink
Improve Oracle Cloud Identity Domain OpenID Connect integration (#1873)
Browse files Browse the repository at this point in the history
  • Loading branch information
sdelamo authored Nov 29, 2024
1 parent f406f82 commit 06ddf39
Show file tree
Hide file tree
Showing 16 changed files with 417 additions and 29 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import io.micronaut.core.annotation.NonNull;
import io.micronaut.core.annotation.Nullable;
import io.micronaut.security.token.Claims;
import io.micronaut.security.token.ClaimsUtils;
import jakarta.inject.Singleton;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
Expand Down Expand Up @@ -65,7 +66,7 @@ public boolean validate(@NonNull Claims claims, @Nullable T request) {
}
return false;
}
if (!expectedIssuer.equals(issuerObject.toString())) {
if (!ClaimsUtils.endsWithIgnoringProtocolAndTrailingSlash(expectedIssuer, issuerObject.toString())) {
if (LOG.isTraceEnabled()) {
LOG.trace("Expected JWT issuer claim of '{}', but found '{}' instead.", expectedIssuer, issuerObject);
}
Expand Down
2 changes: 2 additions & 0 deletions security-oauth2/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ dependencies {
testAnnotationProcessor(mn.micronaut.inject.java)
testImplementation(mnTest.micronaut.test.junit5)
testRuntimeOnly(libs.junit.jupiter.engine)
testImplementation(platform(mnTest.boms.junit))
testImplementation(libs.junit.jupiter.params)
}
tasks.withType<Test> {
useJUnitPlatform()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import io.micronaut.security.oauth2.configuration.OpenIdClientConfiguration;
import io.micronaut.security.oauth2.endpoint.token.response.OauthAuthenticationMapper;
import io.micronaut.security.token.Claims;
import io.micronaut.security.token.ClaimsUtils;
import jakarta.inject.Singleton;
import java.util.List;
import java.util.Optional;
Expand Down Expand Up @@ -67,7 +68,7 @@ protected Optional<String> openIdClientNameWhichMatchesIssClaim(Authentication a
protected Optional<String> openIdClientNameWhichMatchesIssuer(@NonNull String issuer) {
return openIdClientConfigurations.stream()
.filter(conf -> conf.getIssuer().isPresent())
.filter(conf -> conf.getIssuer().get().toString().startsWith(issuer))
.filter(conf -> ClaimsUtils.endsWithIgnoringProtocolAndTrailingSlash(conf.getIssuer().get().toString(), issuer))
.map(Named::getName)
.findFirst();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import io.micronaut.security.oauth2.configuration.OauthClientConfiguration;
import io.micronaut.security.oauth2.configuration.OpenIdClientConfiguration;
import io.micronaut.security.token.Claims;
import io.micronaut.security.token.ClaimsUtils;
import io.micronaut.security.token.jwt.validator.GenericJwtClaimsValidator;
import io.micronaut.security.token.jwt.validator.JwtClaimsValidatorConfigurationProperties;
import jakarta.inject.Singleton;
Expand Down Expand Up @@ -53,6 +54,7 @@
public class IdTokenClaimsValidator<T> implements GenericJwtClaimsValidator<T> {
protected static final Logger LOG = LoggerFactory.getLogger(IdTokenClaimsValidator.class);
protected static final String AUTHORIZED_PARTY = "azp";
private static final String EMPTY = "";

protected final Collection<OauthClientConfiguration> oauthClientConfigurations;

Expand Down Expand Up @@ -204,7 +206,7 @@ protected boolean validateIssuerAudienceAndAzp(@NonNull Claims claims,
boolean matchesIssuer = matchesIssuer(openIdClientConfiguration, iss).orElse(false);
if (!matchesIssuer) {
if (LOG.isDebugEnabled()) {
LOG.debug("configuration issuer '{}' does not match claim issuer '{}'", openIdClientConfiguration.getIssuer().map(URL::toString).orElse(""), iss);
LOG.debug("configuration issuer '{}' does not match claim issuer '{}'", openIdClientConfiguration.getIssuer().map(URL::toString).orElse(EMPTY), iss);
}
return false;
}
Expand Down Expand Up @@ -237,7 +239,7 @@ protected Optional<Boolean> matchesIssuer(@NonNull OpenIdClientConfiguration ope
@NonNull String iss) {
return openIdClientConfiguration.getIssuer()
.map(URL::toString)
.map(issuer -> issuer.equalsIgnoreCase(iss));
.map(issuer -> ClaimsUtils.endsWithIgnoringProtocolAndTrailingSlash(issuer, iss));
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,33 +25,19 @@
*/
public enum AuthorizationServer {
OKTA,
ORACLE_CLOUD,
COGNITO,
KEYCLOAK,
AUTH0;

private static final String ISSUER_PART_OKTA = "okta";
private static final String ISSUER_PART_COGNITO = "cognito";
private static final String ISSUER_PART_AUTH0 = "auth0";
private static final String ISSUER_PART_KEYCLOAK = "/auth/realms/";

/**
* @param issuer Issuer url
* @return An Authorization Server if it could be infered based on the contents of the issuer or empty if not
*/
* @return An Authorization Server if it could be inferred based on the contents of the issuer or empty if not
* @deprecated Use {@link AuthorizationServerResolver} instead
*/
@Deprecated
@NonNull
public static Optional<AuthorizationServer> infer(@NonNull String issuer) {
if (issuer.contains(ISSUER_PART_OKTA)) {
return Optional.of(AuthorizationServer.OKTA);
}
if (issuer.contains(ISSUER_PART_COGNITO)) {
return Optional.of(AuthorizationServer.COGNITO);
}
if (issuer.contains(ISSUER_PART_AUTH0)) {
return Optional.of(AuthorizationServer.AUTH0);
}
if (issuer.contains(ISSUER_PART_KEYCLOAK)) {
return Optional.of(AuthorizationServer.KEYCLOAK);
}
return Optional.empty();
return Optional.ofNullable(DefaultAuthorizationServerResolver.infer(issuer));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/*
* Copyright 2017-2024 original authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.micronaut.security.oauth2.endpoint.endsession.request;

import io.micronaut.context.annotation.DefaultImplementation;
import io.micronaut.core.annotation.NonNull;

import java.util.Optional;

/**
* API to resolve an {@link AuthorizationServer} based on the issuer url.
* @author Sergio del Amo
* @since 4.12.0
*/
@FunctionalInterface
@DefaultImplementation(DefaultAuthorizationServerResolver.class)
public interface AuthorizationServerResolver {
/**
*
* @param issuer OpenID Authorization Server issuer
* @return Based on substrings of the issuer url, it returns an {@link AuthorizationServer}.
*/
@NonNull
Optional<AuthorizationServer> resolve(@NonNull String issuer);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
/*
* Copyright 2017-2024 original authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.micronaut.security.oauth2.endpoint.endsession.request;

import io.micronaut.core.annotation.Internal;
import io.micronaut.core.annotation.NonNull;
import io.micronaut.core.annotation.Nullable;
import jakarta.inject.Singleton;

import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

/**
* {@link io.micronaut.context.annotation.DefaultImplementation} of {@link AuthorizationServerResolver}.
* Based on substrings of the issuer url it returns an {@link AuthorizationServer}.
* @author Sergio del Amo
* @since 4.12.0
*/
@Internal
@Singleton
final class DefaultAuthorizationServerResolver implements AuthorizationServerResolver {
private static final String ISSUER_PART_OKTA = "okta";
private static final String ISSUER_PART_ORACLE_CLOUD = "oraclecloud";
private static final String ISSUER_PART_COGNITO = "cognito";
private static final String ISSUER_PART_AUTH0 = "auth0";
private static final String ISSUER_PART_KEYCLOAK = "/auth/realms/";
private static final Map<String, AuthorizationServer> cache = new ConcurrentHashMap<>();

@Override
@NonNull
public Optional<AuthorizationServer> resolve(@NonNull String issuer) {
return Optional.ofNullable(cache.computeIfAbsent(issuer, DefaultAuthorizationServerResolver::infer));
}

@Nullable
static AuthorizationServer infer (@NonNull String issuer) {
if (issuer.contains(ISSUER_PART_ORACLE_CLOUD)) {
return AuthorizationServer.ORACLE_CLOUD;
}
if (issuer.contains(ISSUER_PART_OKTA)) {
return AuthorizationServer.OKTA;
}
if (issuer.contains(ISSUER_PART_COGNITO)) {
return AuthorizationServer.COGNITO;
}
if (issuer.contains(ISSUER_PART_AUTH0)) {
return AuthorizationServer.AUTH0;
}
if (issuer.contains(ISSUER_PART_KEYCLOAK)) {
return AuthorizationServer.KEYCLOAK;
}
return null;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import io.micronaut.security.oauth2.configuration.OpenIdClientConfiguration;
import io.micronaut.security.oauth2.endpoint.endsession.response.EndSessionCallbackUrlBuilder;
import io.micronaut.security.token.reader.TokenResolver;
import jakarta.inject.Inject;
import jakarta.inject.Singleton;
import java.net.URL;
import java.util.Optional;
Expand All @@ -43,12 +44,24 @@ public class EndSessionEndpointResolver {
private static final Logger LOG = LoggerFactory.getLogger(EndSessionEndpointResolver.class);

private final BeanContext beanContext;
private final AuthorizationServerResolver authorizationServerResolver;

/**
* @param beanContext The bean context
* @param authorizationServerResolver The authorization server resolver
*/
public EndSessionEndpointResolver(BeanContext beanContext) {
@Inject
public EndSessionEndpointResolver(BeanContext beanContext, AuthorizationServerResolver authorizationServerResolver) {
this.beanContext = beanContext;
this.authorizationServerResolver = authorizationServerResolver;
}

/**
* @param beanContext The bean context
*/
@Deprecated
public EndSessionEndpointResolver(BeanContext beanContext) {
this(beanContext, new DefaultAuthorizationServerResolver());
}

/**
Expand Down Expand Up @@ -120,17 +133,18 @@ private Optional<EndSessionEndpoint> getEndSessionEndpoint(OauthClientConfigurat
EndSessionCallbackUrlBuilder endSessionCallbackUrlBuilder,
@NonNull String providerName,
@NonNull String issuer) {
Optional<AuthorizationServer> inferOptional = AuthorizationServer.infer(issuer);
Optional<AuthorizationServer> inferOptional = authorizationServerResolver.resolve(issuer);
if (!inferOptional.isPresent()) {
if (LOG.isDebugEnabled()) {
LOG.debug("No EndSessionEndpoint can be resolved. The issuer for provider [{}] does not match any of the providers supported by default", providerName);
}
return Optional.empty();
}
switch (inferOptional.get()) {
case OKTA:
// Oracle Cloud Logout https://docs.oracle.com/en/cloud/paas/identity-cloud/rest-api/op-oauth2-v1-userlogout-get.html
case ORACLE_CLOUD, OKTA:
if (LOG.isDebugEnabled()) {
LOG.debug("Resolved the OktaEndSessionEndpoint for provider [{}]", providerName);
LOG.debug("Resolved auth server {} for provider [{}]", inferOptional.get(), providerName);
}
return oktaEndSessionEndpoint(oauthClientConfiguration, openIdProviderMetadata, endSessionCallbackUrlBuilder);
case COGNITO:
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,38 @@
package io.micronaut.security.oauth2.client

import io.micronaut.security.oauth2.configuration.OauthClientConfiguration
import io.micronaut.security.oauth2.configuration.OauthClientConfigurationProperties
import io.micronaut.security.testutils.ApplicationContextSpecification
import spock.lang.Unroll

class IdTokenClaimsValidatorSpec extends ApplicationContextSpecification {

void "by default no bean of type IdTokenClaimsValidator exists"() {
expect:
!applicationContext.containsBean(IdTokenClaimsValidator)
}

@Unroll
void "issuer IdTokenClaimsValidator"(String configIss, String iss) {
given:
def oauthClientConfiguration = new OauthClientConfigurationProperties("oci");
def openId = new OauthClientConfigurationProperties.OpenIdClientConfigurationProperties("oci");
openId.setIssuer(new URL(configIss))
oauthClientConfiguration.setOpenid(openId)
List<OauthClientConfiguration> l = List.of(oauthClientConfiguration)
IdTokenClaimsValidator claimsValidator = new IdTokenClaimsValidator(List.of(l))

when:
Optional<Boolean> validation = claimsValidator.matchesIssuer(openId, iss)

then:
validation.isPresent()
validation.get() == true

where:
configIss | iss
"https://idcs-227ebfb7094445cc5a3fbc0faa1fe87b.identity.oraclecloud.com" | "https://identity.oraclecloud.com/"
"https://idcs-227ebfb7094445cc5a3fbc0faa1fe87b.identity.oraclecloud.com" | "https://identity.oraclecloud.com"
"https://identity.oraclecloud.com" | "https://identity.oraclecloud.com"
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ class AuthorizationServerSpec extends Specification {
"https://dev-XXXXX.oktapreview.com/oauth2/default" || AuthorizationServer.OKTA
"https://cognito-idp.us-east-1.amazonaws.com/12345}/" || AuthorizationServer.COGNITO
"https://micronautguides.eu.auth0.com" || AuthorizationServer.AUTH0
"https://identity.oraclecloud.com/" || AuthorizationServer.ORACLE_CLOUD
}

void "Infer authorization server based on the issuer url may return empty Optional"() {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package io.micronaut.security.oauth2.endpoint.endsession.request;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import io.micronaut.test.extensions.junit5.annotation.MicronautTest;
import jakarta.inject.Inject;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.*;
import static org.junit.jupiter.params.provider.Arguments.arguments;

@MicronautTest(startApplication = false)
class AuthorizationServerResolverTest {

@Inject
AuthorizationServerResolver resolver;

static Stream<Arguments> paramsProvider() {
return Stream.of(
arguments("http://localhost:8180/auth/realms/master", AuthorizationServer.KEYCLOAK),
arguments("https://dev-XXXXX.oktapreview.com/oauth2/default", AuthorizationServer.OKTA),
arguments("https://cognito-idp.us-east-1.amazonaws.com/12345}/", AuthorizationServer.COGNITO),
arguments("https://micronautguides.eu.auth0.com", AuthorizationServer.AUTH0),
arguments("https://identity.oraclecloud.com/", AuthorizationServer.ORACLE_CLOUD));
}

@ParameterizedTest
@MethodSource("paramsProvider")
void inferAuthorizationServer(String issuer, AuthorizationServer authorizationServer) {
assertTrue(resolver.resolve(issuer).isPresent());
assertEquals(authorizationServer, resolver.resolve(issuer).get());
}

@Test
void inferAuthorizationServerBasedOnTheIssuerUrlMayReturnEmptyOptional() {
assertFalse(resolver.resolve("http://localhost:8180/auth").isPresent());
}
}
Loading

0 comments on commit 06ddf39

Please sign in to comment.