-
Notifications
You must be signed in to change notification settings - Fork 155
device code flow #7
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
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
This file was deleted.
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; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 There was a problem hiding this comment. Choose a reason for hiding this commentThe 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"; | ||
} | ||
} | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Nit pick - AcquireTokenByAuthorizationGrantSupplier