Skip to content
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

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -28,19 +28,16 @@
import com.nimbusds.oauth2.sdk.ResourceOwnerPasswordCredentialsGrant;
import com.nimbusds.oauth2.sdk.SAML2BearerGrant;
import com.nimbusds.oauth2.sdk.auth.ClientAuthentication;
import org.apache.commons.codec.binary.Base64;

import java.io.UnsupportedEncodingException;
import org.apache.commons.codec.binary.Base64;;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

class AcquireTokenCallable extends MsalCallable<AuthenticationResult> {
public class AcquireTokenByAuthorisationGrantSupplier extends AuthenticationResultSupplier {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit pick - AcquireTokenByAuthorizationGrantSupplier


private AbstractMsalAuthorizationGrant authGrant;
private ClientAuthentication clientAuth;

AcquireTokenCallable(ClientApplicationBase clientApplication,
AbstractMsalAuthorizationGrant authGrant, ClientAuthentication clientAuth) {
AcquireTokenByAuthorisationGrantSupplier(ClientApplicationBase clientApplication,
AbstractMsalAuthorizationGrant authGrant, ClientAuthentication clientAuth) {
super(clientApplication);
this.authGrant = authGrant;
this.clientAuth = clientAuth;
Expand Down Expand Up @@ -69,51 +66,6 @@ AuthenticationResult execute() throws Exception {
return clientApplication.acquireTokenCommon(this.authGrant, this.clientAuth, this.headers);
}

@Override
void logResult(AuthenticationResult result, ClientDataHttpHeaders headers)
throws NoSuchAlgorithmException, UnsupportedEncodingException {

if (!StringHelper.isBlank(result.getAccessToken())) {

String accessTokenHash = this.computeSha256Hash(result
.getAccessToken());
if (!StringHelper.isBlank(result.getRefreshToken())) {
String refreshTokenHash = this.computeSha256Hash(result
.getRefreshToken());
if(clientApplication.isLogPii()){
clientApplication.log.debug(LogHelper.createMessage(String
.format("Access Token with hash '%s' and Refresh Token with hash '%s' returned",
accessTokenHash, refreshTokenHash),
headers.getHeaderCorrelationIdValue()));
}
else{
clientApplication.log.debug(LogHelper.createMessage("Access Token and Refresh Token were returned",
headers.getHeaderCorrelationIdValue()));
}
}
else {
if(clientApplication.isLogPii()){
clientApplication.log.debug(LogHelper.createMessage(String
.format("Access Token with hash '%s' returned",
accessTokenHash),
headers.getHeaderCorrelationIdValue()));
}
else{
clientApplication.log.debug(LogHelper.createMessage("Access Token was returned",
headers.getHeaderCorrelationIdValue()));
}
}
}
}

private String computeSha256Hash(String input)
throws NoSuchAlgorithmException, UnsupportedEncodingException {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
digest.update(input.getBytes("UTF-8"));
byte[] hash = digest.digest();
return Base64.encodeBase64URLSafeString(hash);
}

/**
* @param authGrant
*/
Expand Down Expand Up @@ -165,7 +117,7 @@ AuthorizationGrant getAuthorizationGrantIntegrated(String userName) throws Excep

// Get the realm information
UserDiscoveryResponse userRealmResponse = UserDiscoveryRequest.execute(
userRealmEndpoint,
userRealmEndpoint,
this.headers.getReadonlyHeaderMap(),
clientApplication.getProxy(),
clientApplication.getSslSocketFactory());
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
// Copyright (c) Microsoft Corporation.
// All rights reserved.
//
// This code is licensed under the MIT License.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files(the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions :
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

package com.microsoft.aad.msal4j;

import com.nimbusds.oauth2.sdk.auth.ClientAuthentication;

import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;

import static com.microsoft.aad.msal4j.AdalErrorCode.AUTHORIZATION_PENDING;

public class AcquireTokenDeviceCodeFlowSupplier extends AuthenticationResultSupplier {

private ClientAuthentication clientAuth;
private String scopes;
private Consumer<DeviceCode> deviceCodeConsumer;
private AtomicReference<CompletableFuture<AuthenticationResult>> futureReference;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would assume these are all relevant on the base object? Any reason those are defined here and not on the base? Especially scope is something I would expect to be everywhere

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is used to support cancellation of long running task - polling of Token and point for device code flow


AcquireTokenDeviceCodeFlowSupplier(PublicClientApplication clientApplication, ClientAuthentication clientAuth,
Set<String> scopes, Consumer<DeviceCode> deviceCodeConsumer,
AtomicReference<CompletableFuture<AuthenticationResult>> futureReference)
{
super(clientApplication);
this.headers = new ClientDataHttpHeaders(clientApplication.getCorrelationId());
this.clientAuth = clientAuth;
this.scopes = String.join(" ", scopes);
this.deviceCodeConsumer = deviceCodeConsumer;

this.futureReference = futureReference;
}

AuthenticationResult execute() throws Exception {

clientApplication.authenticationAuthority.doInstanceDiscovery(clientApplication.isValidateAuthority(),
headers.getReadonlyHeaderMap(), clientApplication.getProxy(), clientApplication.getSslSocketFactory());

DeviceCode deviceCode = DeviceCodeRequest.execute(clientApplication.authenticationAuthority.getDeviceCodeEndpoint(),
clientAuth.getClientID().toString(), scopes, headers.getReadonlyHeaderMap(), clientApplication.getProxy(),
clientApplication.getSslSocketFactory());

deviceCodeConsumer.accept(deviceCode);

MsalDeviceCodeAuthorizationGrant deviceCodeGrant =
new MsalDeviceCodeAuthorizationGrant(deviceCode, deviceCode.getScopes());

long expirationTimeInSeconds =
TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()) + deviceCode.getExpiresIn();

AcquireTokenByAuthorisationGrantSupplier acquireTokenByAuthorisationGrantSupplier =
new AcquireTokenByAuthorisationGrantSupplier(clientApplication, deviceCodeGrant, clientAuth);

while (TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()) < expirationTimeInSeconds) {
if(futureReference.get().isCancelled()){
throw new InterruptedException("Acquire token Device Code Flow was interrupted");
}
try {
return acquireTokenByAuthorisationGrantSupplier.execute();
}
catch (AuthenticationException ex) {
if (ex.getErrorCode().equals(AUTHORIZATION_PENDING))
{
TimeUnit.SECONDS.sleep(deviceCode.getInterval());
} else {
throw ex;
}
}
}
throw new AuthenticationException("Expired Device code");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
// Copyright (c) Microsoft Corporation.
// All rights reserved.
//
// This code is licensed under the MIT License.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files(the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions :
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

package com.microsoft.aad.msal4j;

import org.apache.commons.codec.binary.Base64;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.CompletionException;
import java.util.function.Supplier;

abstract class AuthenticationResultSupplier implements Supplier<AuthenticationResult> {

ClientDataHttpHeaders headers;
ClientApplicationBase clientApplication;

AuthenticationResultSupplier(ClientApplicationBase clientApplication) {
this.clientApplication = clientApplication;
}

abstract AuthenticationResult execute() throws Exception;

@Override
public AuthenticationResult get() {
AuthenticationResult result;
try {
result = execute();

logResult(result, headers);
} catch (Exception ex) {
clientApplication.log.error(
LogHelper.createMessage("Execution of " + this.getClass() + " failed.",
this.headers.getHeaderCorrelationIdValue()), ex);

throw new CompletionException(ex);
}
return result;
}

void logResult(AuthenticationResult result, ClientDataHttpHeaders headers)
{
if (!StringHelper.isBlank(result. getAccessToken())) {

String accessTokenHash = this.computeSha256Hash(result
.getAccessToken());
if (!StringHelper.isBlank(result.getRefreshToken())) {
String refreshTokenHash = this.computeSha256Hash(result
.getRefreshToken());
if(clientApplication.isLogPii()){
clientApplication.log.debug(LogHelper.createMessage(String
.format("Access Token with hash '%s' and Refresh Token with hash '%s' returned",
accessTokenHash, refreshTokenHash),
headers.getHeaderCorrelationIdValue()));
}
else{
clientApplication.log.debug(
LogHelper.createMessage("Access Token and Refresh Token were returned",
headers.getHeaderCorrelationIdValue()));
}
}
else {
if(clientApplication.isLogPii()){
clientApplication.log.debug(LogHelper.createMessage(String
.format("Access Token with hash '%s' returned",
accessTokenHash),
headers.getHeaderCorrelationIdValue()));
}
else{
clientApplication.log.debug(LogHelper.createMessage("Access Token was returned",
headers.getHeaderCorrelationIdValue()));
}
}
}
}

private String computeSha256Hash(String input) {
try{
MessageDigest digest = MessageDigest.getInstance("SHA-256");
digest.update(input.getBytes("UTF-8"));
byte[] hash = digest.digest();
return Base64.encodeBase64URLSafeString(hash);
}
catch (NoSuchAlgorithmException | UnsupportedEncodingException ex){
clientApplication.log.warn(
LogHelper.createMessage("Failed to compute SHA-256 hash due to exception - ",
LogHelper.getPiiScrubbedDetails(ex)));
return "Failed to compute SHA-256 hash";
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,7 @@
import java.net.URL;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.function.Supplier;
import java.util.concurrent.*;

/**
* Abstract class containing common API methods and properties.
Expand Down Expand Up @@ -121,23 +117,7 @@ protected CompletableFuture<AuthenticationResult> acquireToken(
final AbstractMsalAuthorizationGrant authGrant,
final ClientAuthentication clientAuth) {

Supplier<AuthenticationResult> supplier = () ->
{
AcquireTokenCallable callable =
new AcquireTokenCallable(this, authGrant, clientAuth);

AuthenticationResult result;
try {
result = callable.execute();
callable.logResult(result, callable.headers);
} catch (Exception ex) {
log.error(LogHelper.createMessage("Execution of " + this.getClass() + " failed.",
callable.headers.getHeaderCorrelationIdValue()), ex);

throw new CompletionException(ex);
}
return result;
};
AcquireTokenByAuthorisationGrantSupplier supplier = new AcquireTokenByAuthorisationGrantSupplier(this, authGrant, clientAuth);

CompletableFuture<AuthenticationResult> future =
executorService != null ? CompletableFuture.supplyAsync(supplier, executorService)
Expand Down
Loading