Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for CIAM custom authority #851

Merged
merged 7 commits into from
Aug 23, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,45 @@ public void acquireTokenWithAuthorizationCode_B2C_Local(String environment) {
assertAcquireTokenB2C(user);
}

@Test
public void acquireTokenWithAuthorizationCode_CiamCud() throws Exception {
String authorityCud = "https://login.msidlabsciam.com/fe362aec-5d43-45d1-b730-9755e60dc3b9/v2.0/";
User user = labUserProvider.getCiamCudUser();

ConfidentialClientApplication cca = ConfidentialClientApplication
.builder(user.getAppId(), CertificateHelper.getClientCertificate())
.oidcAuthority(authorityCud)
.build();

assertEquals("https://login.msidlabsciam.com/fe362aec-5d43-45d1-b730-9755e60dc3b9/v2.0/.well-known/openid-configuration",
cca.authenticationAuthority.canonicalAuthorityUrl.toString());
assertEquals("https://login.msidlabsciam.com/fe362aec-5d43-45d1-b730-9755e60dc3b9/oauth2/v2.0/authorize",
cca.authenticationAuthority.authorizationEndpoint);

String authCode = acquireAuthorizationCodeAutomated(user, cca, null);

IAuthenticationResult result = cca.acquireToken(AuthorizationCodeParameters
.builder(authCode,
new URI(TestConstants.LOCALHOST + httpListener.port()))
.scopes(Collections.singleton("user.read"))
.build())
.get();

assertNotNull(result);
assertNotNull(result.accessToken());
assertNotNull(result.idToken());
assertEquals(user.getUpn(), result.account().username());

IAuthenticationResult resultSilent = cca.acquireTokenSilently(SilentParameters
.builder(Collections.singleton("user.read"), result.account())
.build())
.get();

assertNotNull(resultSilent);
assertEquals(resultSilent.accessToken(), result.accessToken());
assertEquals(resultSilent.account().username(), result.account().username());
}

private void assertAcquireTokenADFS2019(User user) {
PublicClientApplication pca;
try {
Expand Down Expand Up @@ -261,6 +300,8 @@ private String buildAuthenticationCodeURL(AbstractClientApplicationBase app, Map
scope = TestConstants.B2C_LAB_SCOPE;
} else if (authorityType == AuthorityType.ADFS) {
scope = TestConstants.ADFS_SCOPE;
} else if (authorityType == AuthorityType.OIDC) {
scope = TestConstants.USER_READ_SCOPE;
} else {
throw new RuntimeException("Authority type not recognized");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,25 @@ void acquireTokenClientCredentials_ClientSecret_Ciam() throws Exception {
assertNotNull(result.accessToken());
}

@Test
void acquireTokenClientCredentials_Certificate_CiamCud() throws Exception {
bgavrilMS marked this conversation as resolved.
Show resolved Hide resolved
String authorityCud = "https://login.msidlabsciam.com/fe362aec-5d43-45d1-b730-9755e60dc3b9/v2.0/";
String clientId = "b244c86f-ed88-45bf-abda-6b37aa482c79";

ConfidentialClientApplication cca = ConfidentialClientApplication.builder(
clientId, CertificateHelper.getClientCertificate())
.oidcAuthority(authorityCud)
.build();

IAuthenticationResult result = cca.acquireToken(ClientCredentialParameters
.builder(Collections.singleton(TestConstants.DEFAULT_SCOPE))
.build())
.get();

assertNotNull(result);
assertNotNull(result.accessToken());
}

@Test
void acquireTokenClientCredentials_Callback() throws Exception {
String clientId = TestConstants.MSIDLAB_CLIENT_ID;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ void runSeleniumAutomatedLogin(User user, AbstractClientApplicationBase app) {
SeleniumExtensions.performADOrCiamLogin(seleniumDriver, user);
} else if (authorityType == AuthorityType.ADFS) {
SeleniumExtensions.performADFS2019Login(seleniumDriver, user);
} else if (authorityType == AuthorityType.CIAM) {
} else if (authorityType == AuthorityType.CIAM || authorityType == AuthorityType.OIDC) {
SeleniumExtensions.performADOrCiamLogin(seleniumDriver, user);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ public class FederationProvider {
public static final String ADFS_4 = "adfsv4";
public static final String ADFS_2019 = "adfsv2019";
public static final String CIAM = "ciam";
public static final String CIAMCUD = "ciamcud";

}

Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,14 @@ public User getCiamUser() {
return getLabUser(query);
}

public User getCiamCudUser() {
UserQueryParameters query = new UserQueryParameters();
query.parameters.put(UserQueryParameters.FEDERATION_PROVIDER, FederationProvider.CIAMCUD);
query.parameters.put(UserQueryParameters.SIGN_IN_AUDIENCE, "azureadmyorg");

return getLabUser(query);
}

public User getLabUser(UserQueryParameters userQuery) {
if (userCache.containsKey(userQuery)) {
return userCache.get(userQuery);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -242,11 +242,14 @@ private static String getInstanceDiscoveryEndpoint(URL authorityUrl) {
static AadInstanceDiscoveryResponse sendInstanceDiscoveryRequest(URL authorityUrl,
MsalRequest msalRequest,
ServiceBundle serviceBundle) {
IHttpResponse httpResponse;

String instanceDiscoveryRequestUrl = getInstanceDiscoveryEndpoint(authorityUrl) +
formInstanceDiscoveryParameters(authorityUrl);

IHttpResponse httpResponse = executeRequest(instanceDiscoveryRequestUrl, msalRequest.headers().getReadonlyHeaderMap(), msalRequest, serviceBundle);
if (msalRequest.application().authenticationAuthority.authorityType == AuthorityType.OIDC) {
httpResponse = executeRequest(authorityUrl.toString(), msalRequest.headers().getReadonlyHeaderMap(), msalRequest, serviceBundle);
} else {
String instanceDiscoveryRequestUrl = getInstanceDiscoveryEndpoint(authorityUrl) + formInstanceDiscoveryParameters(authorityUrl);
httpResponse = executeRequest(instanceDiscoveryRequestUrl, msalRequest.headers().getReadonlyHeaderMap(), msalRequest, serviceBundle);
}

AadInstanceDiscoveryResponse response = JsonHelper.convertJsonToObject(httpResponse.body(), AadInstanceDiscoveryResponse.class);

Expand Down Expand Up @@ -367,6 +370,22 @@ private static void doInstanceDiscoveryAndCache(URL authorityUrl,
cacheInstanceDiscoveryResponse(authorityUrl.getHost(), aadInstanceDiscoveryResponse);
}

static AadInstanceDiscoveryResponse doOidcInstanceDiscoveryAndCache(OidcAuthority authority, AbstractClientApplicationBase clientApplication, ServiceBundle serviceBundle) {
//This class was originally made under the assumption of only dealing with Azure AD/Entra style endpoints,
// and the expectation that the instance discovery would be done during the first token request.
//Newer features, such as CIAM custom authorities, allow any authority that follows OIDC's standard for an
// instance metadata endpoint, and that endpoint contains data we may need before the first token request.
//Rather than rewrite method signatures in multiple public and private classes or add a lot of duplicate code,
// as a quick and dirty workaround here we just pretend to be in the middle of a token request
RequestContext context = new RequestContext(clientApplication, null, null);
MsalRequest msalRequest = new MsalRequest(clientApplication, null, context) {};

AadInstanceDiscoveryResponse aadInstanceDiscoveryResponse = sendInstanceDiscoveryRequest(authority.canonicalAuthorityUrl, msalRequest, serviceBundle);
cacheInstanceDiscoveryResponse(authority.canonicalAuthorityUrl.getHost(), aadInstanceDiscoveryResponse);

return aadInstanceDiscoveryResponse;
}

private static void validate(AadInstanceDiscoveryResponse aadInstanceDiscoveryResponse) {
if (StringHelper.isBlank(aadInstanceDiscoveryResponse.tenantDiscoveryEndpoint())) {
throw new MsalServiceException(aadInstanceDiscoveryResponse);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,13 @@ class AadInstanceDiscoveryResponse {

@JsonProperty("correlation_id")
private String correlationId;

@JsonProperty("authorization_endpoint")
private String authorizationEndpoint;
Avery-Dunn marked this conversation as resolved.
Show resolved Hide resolved

@JsonProperty("token_endpoint")
private String tokenEndpoint;

@JsonProperty("device_authorization_endpoint")
private String deviceCodeEndpoint;
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,17 @@
package com.microsoft.aad.msal4j;

import com.nimbusds.oauth2.sdk.auth.ClientAuthentication;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.experimental.Accessors;
import org.slf4j.Logger;

import javax.net.ssl.SSLSocketFactory;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URL;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.function.Consumer;

import static com.microsoft.aad.msal4j.ParameterValidationUtils.validateNotBlank;
import static com.microsoft.aad.msal4j.ParameterValidationUtils.validateNotNull;
Expand Down Expand Up @@ -283,6 +278,24 @@ public T b2cAuthority(String val) throws MalformedURLException {
return self();
}

/**
* Set a known authority corresponding to a generic OpenIdConnect Identity Provider.
* MSAL will append ".well-known/openid-configuration" to the authority to retrieve the OIDC metadata and determine the endpoints.
*
* @param val a string value of authority
* @return instance of the Builder on which method was called
*/
public T oidcAuthority(String val) throws MalformedURLException {
authority = Authority.enforceTrailingSlash(val);
URL authorityURL = new URL(authority);

authenticationAuthority = new OidcAuthority(authorityURL);

Authority.validateAuthority(authenticationAuthority.canonicalAuthorityUrl());

return self();
}

/**
* Set a boolean value telling the application if the authority needs to be verified
* against a list of known authorities. Authority is only validated when:
Expand Down Expand Up @@ -545,10 +558,21 @@ public T correlationId(String val) {
builder.httpClient)
);

//In most cases we will retrieve various auth/token/etc. via instance discovery during a token request,
// the format is well known enough to be stored in the codebase itself, or the instance discovery result is
// provided at app creation so we can cache it and skip discovery.
//However, if the authority being set is a generic OIDC authority (rather than Azure AD-style) then we need to perform
// instance discovery when the client app is created, as there are some app-level methods that require the endpoints from
// the instance discovery metadata.
if (aadAadInstanceDiscoveryResponse != null) {
Avery-Dunn marked this conversation as resolved.
Show resolved Hide resolved
AadInstanceDiscoveryProvider.cacheInstanceDiscoveryResponse(
authenticationAuthority.host,
aadAadInstanceDiscoveryResponse);
} else if (authenticationAuthority.authorityType == AuthorityType.OIDC) {
AadInstanceDiscoveryProvider.doOidcInstanceDiscoveryAndCache((OidcAuthority) authenticationAuthority, this, serviceBundle);
((OidcAuthority) authenticationAuthority).setAuthorityProperties(
AadInstanceDiscoveryProvider.doOidcInstanceDiscoveryAndCache(
(OidcAuthority) authenticationAuthority, this, serviceBundle));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
/**
* Represents Authentication Authority responsible for issuing access tokens.
*/

@Accessors(fluent = true)
@Getter(AccessLevel.PACKAGE)
abstract class Authority {
Expand Down Expand Up @@ -63,7 +62,7 @@ static Authority createAuthority(URL authorityUrl) throws MalformedURLException{
createdAuthority = new B2CAuthority(authorityUrl);
} else if (authorityType == AuthorityType.ADFS) {
createdAuthority = new ADFSAuthority(authorityUrl);
} else if(authorityType == AuthorityType.CIAM){
bgavrilMS marked this conversation as resolved.
Show resolved Hide resolved
} else if (authorityType == AuthorityType.CIAM) {
createdAuthority = new CIAMAuthority(authorityUrl);
} else {
throw new IllegalArgumentException("Unsupported Authority Type");
Expand All @@ -79,7 +78,7 @@ static AuthorityType detectAuthorityType(URL authorityUrl) {

final String path = authorityUrl.getPath().substring(1);
if (StringHelper.isBlank(path)) {
if(isCiamAuthority(authorityUrl.getHost())){
if (isCiamAuthority(authorityUrl.getHost())) {
return AuthorityType.CIAM;
}
throw new IllegalArgumentException(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,5 @@
package com.microsoft.aad.msal4j;

enum AuthorityType {
AAD, ADFS, B2C, CIAM
AAD, ADFS, B2C, CIAM, OIDC
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import java.net.MalformedURLException;
import java.net.URL;

public class CIAMAuthority extends Authority{
public class CIAMAuthority extends Authority {
Avery-Dunn marked this conversation as resolved.
Show resolved Hide resolved

public static final String CIAM_HOST_SEGMENT = ".ciamlogin.com";

Expand All @@ -23,20 +23,22 @@ public class CIAMAuthority extends Authority{
CIAMAuthority(URL authorityUrl) throws MalformedURLException {
super(transformAuthority(authorityUrl), AuthorityType.CIAM);
setAuthorityProperties();
this.authority = String.format(CIAM_AUTHORITY_FORMAT,host,tenant);
this.authority = String.format(CIAM_AUTHORITY_FORMAT, host, tenant);
}

/** This method takes a CIAM authority string of format "tenant.ciamlogin.com" or "https://tenant.ciamlogin.com"
and converts it into a full authority url with a path segment of format "/tenant.onmicrosoft.com"
/**
* This method takes a CIAM authority string of format "tenant.ciamlogin.com" or "https://tenant.ciamlogin.com"
* and converts it into a full authority url with a path segment of format "/tenant.onmicrosoft.com"
*
* @param originalAuthority authority to be transformed
* @return full CIAM authority with path
*/
protected static URL transformAuthority(URL originalAuthority) throws MalformedURLException {
String host = originalAuthority.getHost() + originalAuthority.getPath();
String transformedAuthority = originalAuthority.toString();
if(originalAuthority.getPath().equals("/")){
if (originalAuthority.getPath().equals("/")) {
int ciamHostIndex = host.indexOf(CIAMAuthority.CIAM_HOST_SEGMENT);
String tenant = host.substring(0 , ciamHostIndex);
String tenant = host.substring(0, ciamHostIndex);
transformedAuthority = originalAuthority + tenant + ".onmicrosoft.com/";
}
return new URL(transformedAuthority);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

package com.microsoft.aad.msal4j;

import java.net.MalformedURLException;
import java.net.URL;

public class OidcAuthority extends Authority {
//Part of the OpenIdConnect standard, this is appended to the authority to create the endpoint that has OIDC metadata
static final String WELL_KNOWN_OPENID_CONFIGURATION = ".well-known/openid-configuration";
private static final String AUTHORITY_FORMAT = "https://%s/%s/";

OidcAuthority(URL authorityUrl) throws MalformedURLException {
super(transformAuthority(authorityUrl), AuthorityType.OIDC);

this.authority = String.format(AUTHORITY_FORMAT, host, tenant);
}

private static URL transformAuthority(URL originalAuthority) throws MalformedURLException {
Avery-Dunn marked this conversation as resolved.
Show resolved Hide resolved
String transformedAuthority = originalAuthority.toString();
transformedAuthority += WELL_KNOWN_OPENID_CONFIGURATION;

return new URL(transformedAuthority);
}

void setAuthorityProperties(AadInstanceDiscoveryResponse instanceDiscoveryResponse) {
this.authorizationEndpoint = instanceDiscoveryResponse.authorizationEndpoint();
Avery-Dunn marked this conversation as resolved.
Show resolved Hide resolved
this.tokenEndpoint = instanceDiscoveryResponse.tokenEndpoint();
this.deviceCodeEndpoint = instanceDiscoveryResponse.deviceCodeEndpoint();
this.selfSignedJwtAudience = this.tokenEndpoint;
}
}