Skip to content

Sagonzal/update client credentials #377

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

Merged
merged 4 commits into from
Apr 26, 2021
Merged
Show file tree
Hide file tree
Changes from all 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
125 changes: 103 additions & 22 deletions src/integrationtest/java/com.microsoft.aad.msal4j/OnBehalfOfIT.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,35 +11,36 @@

@Test
public class OnBehalfOfIT {
private String accessToken;

private Config cfg;

private void setUp() throws Exception{
LabUserProvider labUserProvider = LabUserProvider.getInstance();
User user = labUserProvider.getDefaultUser(cfg.azureEnvironment);
@Test(dataProvider = "environments", dataProviderClass = EnvironmentsProvider.class)
public void acquireTokenWithOBO_Managed(String environment) throws Exception {
cfg = new Config(environment);
String accessToken = this.getAccessToken();

String clientId = cfg.appProvider.getAppId();
String apiReadScope = cfg.appProvider.getOboAppIdURI() + "/user_impersonation";
final String clientId = cfg.appProvider.getOboAppId();
final String password = cfg.appProvider.getOboAppPassword();

PublicClientApplication pca = PublicClientApplication.builder(
clientId).
authority(cfg.tenantSpecificAuthority()).
build();
ConfidentialClientApplication cca =
ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromSecret(password)).
authority(cfg.tenantSpecificAuthority()).
build();

IAuthenticationResult result = pca.acquireToken(
UserNamePasswordParameters.builder(Collections.singleton(apiReadScope),
user.getUpn(),
user.getPassword().toCharArray()).build()).get();
IAuthenticationResult result =
cca.acquireToken(OnBehalfOfParameters.builder(
Collections.singleton(cfg.graphDefaultScope()),
new UserAssertion(accessToken)).build()).
get();

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

@Test(dataProvider = "environments", dataProviderClass = EnvironmentsProvider.class)
public void acquireTokenWithOBO_Managed(String environment) throws Exception {
public void acquireTokenWithOBO_testCache(String environment) throws Exception {
cfg = new Config(environment);

setUp();
String accessToken = this.getAccessToken();

final String clientId = cfg.appProvider.getOboAppId();
final String password = cfg.appProvider.getOboAppPassword();
Expand All @@ -49,14 +50,94 @@ public void acquireTokenWithOBO_Managed(String environment) throws Exception {
authority(cfg.tenantSpecificAuthority()).
build();

IAuthenticationResult result =
IAuthenticationResult result1 =
cca.acquireToken(OnBehalfOfParameters.builder(
Collections.singleton(TestConstants.USER_READ_SCOPE),
new UserAssertion(accessToken)).build()).
get();

Assert.assertNotNull(result1);
Assert.assertNotNull(result1.accessToken());

// Same scope and userAssertion, should return cached tokens
IAuthenticationResult result2 =
cca.acquireToken(OnBehalfOfParameters.builder(
Collections.singleton(TestConstants.USER_READ_SCOPE),
new UserAssertion(accessToken)).build()).
get();

Assert.assertEquals(result1.accessToken(), result2.accessToken());

// Scope 2, should return new token
IAuthenticationResult result3 =
cca.acquireToken(OnBehalfOfParameters.builder(
Collections.singleton(cfg.graphDefaultScope()),
new UserAssertion(accessToken)).build()).
get();

Assert.assertNotNull(result);
Assert.assertNotNull(result.accessToken());
Assert.assertNotNull(result.idToken());
Assert.assertNotNull(result3);
Assert.assertNotNull(result3.accessToken());
Assert.assertNotEquals(result2.accessToken(), result3.accessToken());

// Scope 2, should return cached token
IAuthenticationResult result4 =
cca.acquireToken(OnBehalfOfParameters.builder(
Collections.singleton(cfg.graphDefaultScope()),
new UserAssertion(accessToken)).build()).
get();

Assert.assertEquals(result3.accessToken(), result4.accessToken());

// skipCache=true, should return new token
IAuthenticationResult result5 =
cca.acquireToken(
OnBehalfOfParameters.builder(
Collections.singleton(cfg.graphDefaultScope()),
new UserAssertion(accessToken))
.skipCache(true)
.build()).
get();

Assert.assertNotNull(result5);
Assert.assertNotNull(result5.accessToken());
Assert.assertNotEquals(result5.accessToken(), result4.accessToken());
Assert.assertNotEquals(result5.accessToken(), result2.accessToken());


String newAccessToken = this.getAccessToken();
// New new UserAssertion, should return new token
IAuthenticationResult result6 =
cca.acquireToken(
OnBehalfOfParameters.builder(
Collections.singleton(cfg.graphDefaultScope()),
new UserAssertion(newAccessToken))
.build()).
get();

Assert.assertNotNull(result6);
Assert.assertNotNull(result6.accessToken());
Assert.assertNotEquals(result6.accessToken(), result5.accessToken());
Assert.assertNotEquals(result6.accessToken(), result4.accessToken());
Assert.assertNotEquals(result6.accessToken(), result2.accessToken());
}

private String getAccessToken() throws Exception {

LabUserProvider labUserProvider = LabUserProvider.getInstance();
User user = labUserProvider.getDefaultUser(cfg.azureEnvironment);

String clientId = cfg.appProvider.getAppId();
String apiReadScope = cfg.appProvider.getOboAppIdURI() + "/user_impersonation";
PublicClientApplication pca = PublicClientApplication.builder(
clientId).
authority(cfg.tenantSpecificAuthority()).
build();

IAuthenticationResult result = pca.acquireToken(
UserNamePasswordParameters.builder(Collections.singleton(apiReadScope),
user.getUpn(),
user.getPassword().toCharArray()).build()).get();

return result.accessToken();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,8 @@ public CompletableFuture<IAuthenticationResult> acquireTokenSilently(SilentParam
SilentRequest silentRequest = new SilentRequest(
parameters,
this,
createRequestContext(PublicApi.ACQUIRE_TOKEN_SILENTLY, parameters));
createRequestContext(PublicApi.ACQUIRE_TOKEN_SILENTLY, parameters),
null);

return executeRequest(silentRequest);
}
Expand Down Expand Up @@ -250,10 +251,14 @@ private AuthenticationResultSupplier getAuthenticationResultSupplier(MsalRequest
supplier = new AcquireTokenByInteractiveFlowSupplier(
(PublicClientApplication) this,
(InteractiveRequest) msalRequest);
} else if(msalRequest instanceof ClientCredentialRequest){
} else if(msalRequest instanceof ClientCredentialRequest) {
supplier = new AcquireTokenByClientCredentialSupplier(
(ConfidentialClientApplication) this,
(ClientCredentialRequest) msalRequest);
} else if(msalRequest instanceof OnBehalfOfRequest){
supplier = new AcquireTokenByOnBehalfOfSupplier(
(ConfidentialClientApplication) this,
(OnBehalfOfRequest) msalRequest);
} else {
supplier = new AcquireTokenByAuthorizationGrantSupplier(
this,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,9 @@ class AccountCacheEntity implements Serializable {
@JsonProperty("client_info")
protected String clientInfoStr;

@JsonProperty("user_assertion_hash")
protected String userAssertionHash;

ClientInfo clientInfo() {
return ClientInfo.createFromJson(clientInfoStr);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class AcquireTokenByClientCredentialSupplier extends AuthenticationResultSupplier {
class AcquireTokenByClientCredentialSupplier extends AuthenticationResultSupplier {

private final static Logger LOG = LoggerFactory.getLogger(AcquireTokenByClientCredentialSupplier.class);
private ClientCredentialRequest clientCredentialRequest;
Expand All @@ -31,7 +31,8 @@ AuthenticationResult execute() throws Exception {
SilentRequest silentRequest = new SilentRequest(
parameters,
this.clientApplication,
this.clientApplication.createRequestContext(PublicApi.ACQUIRE_TOKEN_SILENTLY, parameters));
this.clientApplication.createRequestContext(PublicApi.ACQUIRE_TOKEN_SILENTLY, parameters),
null);

AcquireTokenSilentSupplier supplier = new AcquireTokenSilentSupplier(
this.clientApplication,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

package com.microsoft.aad.msal4j;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

class AcquireTokenByOnBehalfOfSupplier extends AuthenticationResultSupplier {

private final static Logger LOG = LoggerFactory.getLogger(AcquireTokenByOnBehalfOfSupplier.class);
private OnBehalfOfRequest onBehalfOfRequest;

AcquireTokenByOnBehalfOfSupplier(ConfidentialClientApplication clientApplication,
OnBehalfOfRequest onBehalfOfRequest) {
super(clientApplication, onBehalfOfRequest);
this.onBehalfOfRequest = onBehalfOfRequest;
}

@Override
AuthenticationResult execute() throws Exception {
if (onBehalfOfRequest.parameters.skipCache() != null &&
!onBehalfOfRequest.parameters.skipCache()) {
LOG.info("SkipCache set to false. Attempting cache lookup");
try {
SilentParameters parameters = SilentParameters
.builder(this.onBehalfOfRequest.parameters.scopes())
.claims(this.onBehalfOfRequest.parameters.claims())
.build();

SilentRequest silentRequest = new SilentRequest(
parameters,
this.clientApplication,
this.clientApplication.createRequestContext(PublicApi.ACQUIRE_TOKEN_SILENTLY, parameters),
onBehalfOfRequest.parameters.userAssertion());

AcquireTokenSilentSupplier supplier = new AcquireTokenSilentSupplier(
this.clientApplication,
silentRequest);

return supplier.execute();
} catch (MsalClientException ex) {
LOG.debug(String.format("Cache lookup failed: %s", ex.getMessage()));
return acquireTokenOnBehalfOf();
}
}

LOG.info("SkipCache set to true. Skipping cache lookup and attempting on-behalf-of request");
return acquireTokenOnBehalfOf();
}

private AuthenticationResult acquireTokenOnBehalfOf() throws Exception {
AcquireTokenByAuthorizationGrantSupplier supplier = new AcquireTokenByAuthorizationGrantSupplier(
this.clientApplication,
onBehalfOfRequest,
null);

return supplier.execute();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@ AuthenticationResult execute() throws Exception {
res = clientApplication.tokenCache.getCachedAuthenticationResult(
requestAuthority,
silentRequest.parameters().scopes(),
clientApplication.clientId());
clientApplication.clientId(),
silentRequest.assertion());
} else {
res = clientApplication.tokenCache.getCachedAuthenticationResult(
silentRequest.parameters().account(),
Expand Down
3 changes: 3 additions & 0 deletions src/main/java/com/microsoft/aad/msal4j/Credential.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,7 @@ class Credential {

@JsonProperty("secret")
protected String secret;

@JsonProperty("user_assertion_hash")
protected String userAssertionHash;
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
* For details see https://aka.ms/msal4jclientapplications
*/
public interface IConfidentialClientApplication extends IClientApplicationBase {

/**
* @return a boolean value which determines whether x5c claim (public key of the certificate)
* will be sent to the STS.
Expand All @@ -30,8 +31,18 @@ public interface IConfidentialClientApplication extends IClientApplicationBase {
/**
* Acquires an access token for this application (usually a Web API) from the authority configured
* in the application, in order to access another downstream protected Web API on behalf of a user
* using the On-Behalf-Of flow. This confidential client application was itself called with a token
* which will be provided in the {@link UserAssertion} to the {@link OnBehalfOfParameters}
* using the On-Behalf-Of flow. It will by default attempt to get tokens from the token cache.
* This confidential client application was itself called with an acces token which is provided in
* the {@link UserAssertion} field of {@link OnBehalfOfParameters}.
*
* When serializing/deserializing the in-memory token cache to permanent storage, there should be
* a token cache per incoming access token, where the hash of the incoming access token can be used
* as the token cache key. Access tokens are usually only valid for a 1 hour period of time,
* and a new access token in the {@link UserAssertion} means there will be a new token cache and
* new token cache key. To avoid your permanent storage from being filled with expired
* token caches, an eviction policy should be set. For example, a token cache that
* is more than a couple of hours old can be deemed expired and therefore evicted from the
* serialized token cache.
* @param parameters instance of {@link OnBehalfOfParameters}
* @return {@link CompletableFuture} containing an {@link IAuthenticationResult}
*/
Expand Down
5 changes: 5 additions & 0 deletions src/main/java/com/microsoft/aad/msal4j/IUserAssertion.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,9 @@ public interface IUserAssertion {
* @return string value
*/
String getAssertion();

/**
* @return Base64 encoded SHA256 hash of the assertion
*/
String getAssertionHash();
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,13 @@ public class OnBehalfOfParameters implements IApiParameters {
*/
private ClaimsRequest claims;

/**
* Indicates whether the request should skip looking into the token cache. Be default it is
* set to false.
*/
@Builder.Default
private Boolean skipCache = false;

@NonNull
private IUserAssertion userAssertion;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,13 @@
@Getter
class OnBehalfOfRequest extends MsalRequest {

OnBehalfOfParameters parameters;

OnBehalfOfRequest(OnBehalfOfParameters parameters,
ConfidentialClientApplication application,
RequestContext requestContext) {
super(application, createAuthenticationGrant(parameters), requestContext);
this.parameters = parameters;
}

private static OAuthAuthorizationGrant createAuthenticationGrant(OnBehalfOfParameters parameters) {
Expand Down
6 changes: 4 additions & 2 deletions src/main/java/com/microsoft/aad/msal4j/SilentRequest.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,18 @@
class SilentRequest extends MsalRequest {

private SilentParameters parameters;

private IUserAssertion assertion;
private Authority requestAuthority;

SilentRequest(SilentParameters parameters,
AbstractClientApplicationBase application,
RequestContext requestContext) throws MalformedURLException {
RequestContext requestContext,
IUserAssertion assertion) throws MalformedURLException {

super(application, null, requestContext);

this.parameters = parameters;
this.assertion = assertion;
this.requestAuthority = StringHelper.isBlank(parameters.authorityUrl()) ?
application.authenticationAuthority :
Authority.createAuthority(new URL(parameters.authorityUrl()));
Expand Down
Loading