Skip to content
This repository has been archived by the owner on Jun 30, 2023. It is now read-only.

Commit

Permalink
Fix for #1463 - More strict token cache removal when using several re…
Browse files Browse the repository at this point in the history
…sources
  • Loading branch information
jennyf19 authored and bgavrilMS committed Jan 11, 2019
1 parent d26dfdf commit a0859c3
Show file tree
Hide file tree
Showing 14 changed files with 462 additions and 412 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -23,28 +23,31 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//------------------------------------------------------------------------------
//

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Identity.Core;
using Microsoft.Identity.Core.Cache;
using Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.Platform;
using System;

namespace Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.Platform
namespace Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.Broker
{
internal class BrokerHelper
internal class BrokerFactory
{
public RequestContext RequestContext { get; set; }
public IPlatformParameters PlatformParameters { get; set; }

public bool CanInvokeBroker { get { return false; } }

public Task<AdalResultWrapper> AcquireTokenUsingBrokerAsync(IDictionary<string, string> brokerPayload)
// thread safety ensured by implicit LazyThreadSafetyMode.ExecutionAndPublication
public static IBroker CreateBrokerFacade(ICoreLogger logger)
{
throw new NotImplementedException();
if (logger == null)
{
throw new ArgumentNullException(nameof(logger));
}
#if ANDROID
return new AndroidBroker(logger);
#elif iOS
return new iOSBroker(logger);
#else
return new NullBroker();
#endif
}
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
//----------------------------------------------------------------------
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Identity.Core.Cache;

//----------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation.
// All rights reserved.
Expand All @@ -23,26 +27,16 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//------------------------------------------------------------------------------

using Microsoft.Identity.Core;
using Microsoft.Identity.Core.Cache;
using System.Collections.Generic;
using System.Threading.Tasks;
//

namespace Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.Platform
namespace Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.Broker
{
internal class BrokerHelper
internal interface IBroker
{
public RequestContext RequestContext { get; set; }

public IPlatformParameters PlatformParameters { get; set; }
bool CanInvokeBroker { get; }

public bool CanInvokeBroker { get { return false; } }
IPlatformParameters PlatformParameters { get; set; } //todo: remove setter, initialize broker with PlatformParams

public Task<AdalResultWrapper> AcquireTokenUsingBrokerAsync(IDictionary<string, string> brokerPayload)
{
throw new System.NotImplementedException();
}
Task<AdalResultWrapper> AcquireTokenUsingBrokerAsync(IDictionary<string, string> brokerPayload);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Identity.Core.Cache;

namespace Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.Broker
{
/// <summary>
/// For platforms that do not support a broker (net desktop, net core, UWP, netstandard)
/// </summary>
internal class NullBroker : IBroker
{
public bool CanInvokeBroker => false;

public IPlatformParameters PlatformParameters
{
get; set;
}

public Task<AdalResultWrapper> AcquireTokenUsingBrokerAsync(IDictionary<string, string> brokerPayload)
{
throw new NotImplementedException();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
using Microsoft.Identity.Core.Cache;
using Microsoft.Identity.Core.Helpers;
using Microsoft.Identity.Core.OAuth2;
using Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.Broker;
using Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.Cache;
using Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.ClientCreds;
using Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.Helpers;
Expand All @@ -49,17 +50,16 @@ internal abstract class AcquireTokenHandlerBase
protected static readonly Task CompletedTask = Task.FromResult(false);
internal readonly IDictionary<string, string> BrokerParameters;
protected CacheQueryData CacheQueryData = new CacheQueryData();
protected readonly BrokerHelper BrokerHelper = new BrokerHelper();
protected readonly IBroker brokerHelper;
private AdalHttpClient _client = null;
private readonly TokenCache _tokenCache;
internal readonly RequestContext RequestContext;

protected AcquireTokenHandlerBase(RequestData requestData)
{
Authenticator = requestData.Authenticator;
_tokenCache = requestData.TokenCache;
RequestContext = CreateCallState(null, this.Authenticator.CorrelationId);
BrokerHelper.RequestContext = RequestContext;
brokerHelper = BrokerFactory.CreateBrokerFacade(RequestContext.Logger);

RequestContext.Logger.Info(string.Format(CultureInfo.CurrentCulture,
"ADAL {0} with assembly version '{1}', file version '{2}' and informational version '{3}' is running...",
Expand Down Expand Up @@ -167,9 +167,10 @@ public async Task<AuthenticationResult> RunAsync()
ResultEx = await _tokenCache.LoadFromCacheAsync(CacheQueryData, RequestContext).ConfigureAwait(false);
extendedLifetimeResultEx = ResultEx;

// Check if we need to get an AT from the RT
if (ResultEx?.Result != null &&
(ResultEx.Result.AccessToken == null && ResultEx.RefreshToken != null ||
ResultEx.Result.ExtendedLifeTimeToken && ResultEx.RefreshToken != null))
((ResultEx.Result.AccessToken == null && ResultEx.RefreshToken != null) ||
(ResultEx.Result.ExtendedLifeTimeToken && ResultEx.RefreshToken != null)))
{
ResultEx = await RefreshAccessTokenAsync(ResultEx).ConfigureAwait(false);
if (ResultEx != null && ResultEx.Exception == null)
Expand All @@ -178,7 +179,7 @@ public async Task<AuthenticationResult> RunAsync()
}
}
}

if (ResultEx == null || ResultEx.Exception != null)
{
if (BrokerHelper.CanInvokeBroker)
Expand All @@ -202,7 +203,8 @@ public async Task<AuthenticationResult> RunAsync()
notifiedBeforeAccessCache = await StoreResultExToCacheAsync(notifiedBeforeAccessCache).ConfigureAwait(false);
}

await PostRunAsync(ResultEx.Result).ConfigureAwait(false);
// At this point we have an Acess Token - return it
await this.PostRunAsync(ResultEx.Result).ConfigureAwait(false);
return new AuthenticationResult(ResultEx.Result);
}
catch (Exception ex)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,63 +37,55 @@
using Microsoft.Identity.Core.Cache;
using Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.OAuth2;
using Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.Helpers;
using Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.Broker;

namespace Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.Platform
{
[Android.Runtime.Preserve(AllMembers = true)]
internal class BrokerHelper
internal class AndroidBroker : IBroker
{
private static SemaphoreSlim readyForResponse = null;
private static AdalResultWrapper resultEx = null;

private readonly BrokerProxy mBrokerProxy = new BrokerProxy(Application.Context);
private readonly AndroidBrokerProxy _brokerProxy;
private readonly ICoreLogger _logger;

public RequestContext RequestContext { get; set; }
public AndroidBroker(ICoreLogger logger)
{
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_brokerProxy = new AndroidBrokerProxy(Application.Context, logger);
}

public IPlatformParameters PlatformParameters { get; set; }

private bool WillUseBroker()
{
PlatformParameters pp = PlatformParameters as PlatformParameters;
if (pp != null)
{
return pp.UseBroker;
}

return false;
}

public bool CanInvokeBroker
{
get
{
mBrokerProxy.RequestContext = RequestContext;
return WillUseBroker() && mBrokerProxy.CanSwitchToBroker();
{
return WillUseBroker() && _brokerProxy.CanSwitchToBroker();
}
}

public async Task<AdalResultWrapper> AcquireTokenUsingBrokerAsync(IDictionary<string, string> brokerPayload)
{
mBrokerProxy.RequestContext = RequestContext;

resultEx = null;
readyForResponse = new SemaphoreSlim(0);
try
{
await Task.Run(() => AcquireToken(brokerPayload)).ConfigureAwait(false);
await Task.Run(() => AcquireTokenInternal(brokerPayload)).ConfigureAwait(false);
}
catch (Exception ex)
{
RequestContext.Logger.ErrorPii(ex);
_logger.ErrorPii(ex);
throw;
}
await readyForResponse.WaitAsync().ConfigureAwait(false);
return resultEx;
}

public void AcquireToken(IDictionary<string, string> brokerPayload)
private void AcquireTokenInternal(IDictionary<string, string> brokerPayload)
{

if (brokerPayload.ContainsKey(BrokerParameter.BrokerInstallUrl))
{
string url = brokerPayload[BrokerParameter.BrokerInstallUrl];
Expand All @@ -118,10 +110,10 @@ public void AcquireToken(IDictionary<string, string> brokerPayload)

// BROKER flow intercepts here
// cache and refresh call happens through the authenticator service
if (mBrokerProxy.VerifyUser(request.LoginHint,
if (_brokerProxy.VerifyUser(request.LoginHint,
request.UserId))
{
RequestContext.Logger.Verbose("It switched to broker for context: " + mContext.PackageName);
_logger.Verbose("It switched to broker for context: " + mContext.PackageName);

request.BrokerAccountName = request.LoginHint;

Expand All @@ -130,18 +122,18 @@ public void AcquireToken(IDictionary<string, string> brokerPayload)
bool hasAccountNameOrUserId = !string.IsNullOrEmpty(request.BrokerAccountName) || !string.IsNullOrEmpty(request.UserId);
if (string.IsNullOrEmpty(request.Claims) && hasAccountNameOrUserId)
{
RequestContext.Logger.Verbose("User is specified for background token request");
_logger.Verbose("User is specified for background token request");

resultEx = mBrokerProxy.GetAuthTokenInBackground(request, platformParams.CallerActivity);
resultEx = _brokerProxy.GetAuthTokenInBackground(request, platformParams.CallerActivity);
}
else
{
RequestContext.Logger.Verbose("User is not specified for background token request");
_logger.Verbose("User is not specified for background token request");
}

if (resultEx != null && resultEx.Result != null && !string.IsNullOrEmpty(resultEx.Result.AccessToken))
{
RequestContext.Logger.Verbose("Token is returned from background call");
_logger.Verbose("Token is returned from background call");
readyForResponse.Release();
return;
}
Expand All @@ -151,16 +143,16 @@ public void AcquireToken(IDictionary<string, string> brokerPayload)
// Initial request to authenticator needs to launch activity to
// record calling uid for the account. This happens for Prompt auto
// or always behavior.
RequestContext.Logger.Verbose("Token is not returned from backgroud call");
_logger.Verbose("Token is not returned from backgroud call");

// Only happens with callback since silent call does not show UI
RequestContext.Logger.Verbose("Launch activity for Authenticator");
_logger.Verbose("Launch activity for Authenticator");

RequestContext.Logger.Verbose("Starting Authentication Activity");
_logger.Verbose("Starting Authentication Activity");

if (resultEx == null)
{
RequestContext.Logger.Verbose("Initial request to authenticator");
_logger.Verbose("Initial request to authenticator");
// Log the initial request but not force a prompt
}

Expand All @@ -172,12 +164,12 @@ public void AcquireToken(IDictionary<string, string> brokerPayload)
// onActivityResult will receive the response
// Activity needs to launch to record calling app for this
// account
Intent brokerIntent = mBrokerProxy.GetIntentForBrokerActivity(request, platformParams.CallerActivity);
Intent brokerIntent = _brokerProxy.GetIntentForBrokerActivity(request, platformParams.CallerActivity);
if (brokerIntent != null)
{
try
{
RequestContext.Logger.Verbose(
_logger.Verbose(
"Calling activity pid:" + Android.OS.Process.MyPid()
+ " tid:" + Android.OS.Process.MyTid() + "uid:"
+ Android.OS.Process.MyUid());
Expand All @@ -186,7 +178,7 @@ public void AcquireToken(IDictionary<string, string> brokerPayload)
}
catch (ActivityNotFoundException e)
{
RequestContext.Logger.ErrorPii(e);
_logger.ErrorPii(e);
}
}
}
Expand Down Expand Up @@ -218,18 +210,30 @@ internal static void SetBrokerResult(Intent data, int resultCode)
ExpiresOn = data.GetLongExtra(BrokerConstants.AccountExpireDate, 0)
};

resultEx = tokenResponse.GetResult(BrokerProxy.ConvertFromTimeT(tokenResponse.ExpiresOn),
BrokerProxy.ConvertFromTimeT(tokenResponse.ExpiresOn));
resultEx = tokenResponse.GetResult(AndroidBrokerProxy.ConvertFromTimeT(tokenResponse.ExpiresOn),
AndroidBrokerProxy.ConvertFromTimeT(tokenResponse.ExpiresOn));
}

readyForResponse.Release();
}
}

internal class CallBackHandler : Java.Lang.Object, IAccountManagerCallback
{
public void Run(IAccountManagerFuture future)

private bool WillUseBroker()
{
PlatformParameters pp = PlatformParameters as PlatformParameters;
if (pp != null)
{
return pp.UseBroker;
}

return false;
}
}

//internal class CallBackHandler : Java.Lang.Object, IAccountManagerCallback
//{
// public void Run(IAccountManagerFuture future)
// {
// }
//}
}
Loading

0 comments on commit a0859c3

Please sign in to comment.