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

Commit

Permalink
Refactor http to reduce static singleton dependencies (#1310)
Browse files Browse the repository at this point in the history
  • Loading branch information
MarkZuber committed Oct 17, 2018
1 parent b88f85b commit 93d88f3
Show file tree
Hide file tree
Showing 159 changed files with 7,561 additions and 6,601 deletions.
192 changes: 192 additions & 0 deletions LibsNoSamples.sln.DotSettings

Large diffs are not rendered by default.

Expand Up @@ -29,7 +29,9 @@
using System.Threading.Tasks;
using Microsoft.Identity.Core;
using Microsoft.Identity.Core.Cache;
using Microsoft.Identity.Core.Http;
using Microsoft.Identity.Core.UI;
using Microsoft.Identity.Core.WsTrust;
using Microsoft.IdentityModel.Clients.ActiveDirectory.Internal;
using Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.ClientCreds;
using Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.Flows;
Expand All @@ -50,6 +52,9 @@ internal enum AuthorityValidationType
/// </summary>
public sealed class AuthenticationContext
{
private readonly IHttpManager _httpManager;
private readonly IWsTrustWebRequestManager _wsTrustWebRequestManager;

static AuthenticationContext()
{
ModuleInitializer.EnsureModuleInitialized();
Expand All @@ -63,7 +68,7 @@ static AuthenticationContext()
/// </summary>
/// <param name="authority">Address of the authority to issue token.</param>
public AuthenticationContext(string authority)
: this(authority, AuthorityValidationType.NotProvided, TokenCache.DefaultShared)
: this(null, authority, AuthorityValidationType.NotProvided, TokenCache.DefaultShared)
{
}

Expand All @@ -74,7 +79,7 @@ public AuthenticationContext(string authority)
/// <param name="authority">Address of the authority to issue token.</param>
/// <param name="validateAuthority">Flag to turn address validation ON or OFF.</param>
public AuthenticationContext(string authority, bool validateAuthority)
: this(authority, validateAuthority ? AuthorityValidationType.True : AuthorityValidationType.False,
: this(null, authority, validateAuthority ? AuthorityValidationType.True : AuthorityValidationType.False,
TokenCache.DefaultShared)
{
}
Expand All @@ -86,7 +91,7 @@ public AuthenticationContext(string authority, bool validateAuthority)
/// <param name="authority">Address of the authority to issue token.</param>
/// <param name="tokenCache">Token cache used to lookup cached tokens on calls to AcquireToken</param>
public AuthenticationContext(string authority, TokenCache tokenCache)
: this(authority, AuthorityValidationType.NotProvided, tokenCache)
: this(null, authority, AuthorityValidationType.NotProvided, tokenCache)
{
}

Expand All @@ -98,18 +103,20 @@ public AuthenticationContext(string authority, TokenCache tokenCache)
/// <param name="validateAuthority">Flag to turn address validation ON or OFF.</param>
/// <param name="tokenCache">Token cache used to lookup cached tokens on calls to AcquireToken</param>
public AuthenticationContext(string authority, bool validateAuthority, TokenCache tokenCache)
: this(authority, validateAuthority ? AuthorityValidationType.True : AuthorityValidationType.False,
: this(null, authority, validateAuthority ? AuthorityValidationType.True : AuthorityValidationType.False,
tokenCache)
{
}

private AuthenticationContext(string authority, AuthorityValidationType validateAuthority,
internal AuthenticationContext(IHttpManager httpManager, string authority, AuthorityValidationType validateAuthority,
TokenCache tokenCache)
{
// If authorityType is not provided (via first constructor), we validate by default (except for ASG and Office tenants).
this.Authenticator = new Authenticator(authority, (validateAuthority != AuthorityValidationType.False));

this.TokenCache = tokenCache;

_httpManager = httpManager ?? new HttpManager();
_wsTrustWebRequestManager = new WsTrustWebRequestManager(_httpManager);
}

/// <summary>
Expand Down Expand Up @@ -173,7 +180,7 @@ public string KeychainSecurityGroup
set
{
keychainSecurityGroup = value;
StorageDelegates.legacyCachePersistance.SetKeychainSecurityGroup(value);
StorageDelegates.LegacyCachePersistence.SetKeychainSecurityGroup(value);
TokenCache.tokenCacheAccessor.SetKeychainSecurityGroup(value);
}
}
Expand Down Expand Up @@ -457,7 +464,7 @@ internal IWebUI CreateWebAuthenticationDialog(PlatformParameters parameters)
ExtendedLifeTimeEnabled = this.ExtendedLifeTimeEnabled
};

var handler = new AcquireTokenUsernamePasswordHandler(requestData, upInput);
var handler = new AcquireTokenUsernamePasswordHandler(_wsTrustWebRequestManager, requestData, upInput);
return await handler.RunAsync().ConfigureAwait(false);
}

Expand All @@ -475,7 +482,7 @@ internal IWebUI CreateWebAuthenticationDialog(PlatformParameters parameters)
ExtendedLifeTimeEnabled = this.ExtendedLifeTimeEnabled
};

var handler = new AcquireTokenIWAHandler(requestData, iwaInput);
var handler = new AcquireTokenIWAHandler(_wsTrustWebRequestManager, requestData, iwaInput);
return await handler.RunAsync().ConfigureAwait(false);
}

Expand Down
Expand Up @@ -49,7 +49,6 @@ internal static class AdalErrorMessageEx
internal static class Constant
{
public const string MsAppScheme = "ms-app";
public static readonly Uri SsoPlaceHolderUri = new Uri("https://sso");
}

/// <summary>
Expand Down
Expand Up @@ -31,6 +31,7 @@
using System.Threading.Tasks;
using Microsoft.Identity.Core;
using Microsoft.Identity.Core.Cache;
using Microsoft.Identity.Core.Helpers;
using Microsoft.Identity.Core.OAuth2;
using Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.Cache;
using Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.ClientCreds;
Expand All @@ -51,7 +52,6 @@ internal abstract class AcquireTokenHandlerBase
protected CacheQueryData CacheQueryData = new CacheQueryData();
protected readonly BrokerHelper brokerHelper = new BrokerHelper();
private AdalHttpClient client = null;
protected PlatformInformation platformInformation = new PlatformInformation();
internal readonly RequestContext RequestContext;

protected AcquireTokenHandlerBase(RequestData requestData)
Expand All @@ -62,8 +62,8 @@ protected AcquireTokenHandlerBase(RequestData requestData)

RequestContext.Logger.Info(string.Format(CultureInfo.CurrentCulture,
"ADAL {0} with assembly version '{1}', file version '{2}' and informational version '{3}' is running...",
platformInformation.GetProductName(), AdalIdHelper.GetAdalVersion(),
AdalIdHelper.GetAssemblyFileVersion(), AdalIdHelper.GetAssemblyInformationalVersion()));
PlatformProxyFactory.GetPlatformProxy().GetProductName(), AdalIdHelper.GetAdalVersion(),
AssemblyUtils.GetAssemblyFileVersionAttribute(), AssemblyUtils.GetAssemblyInformationalVersion()));

{
string msg = string.Format(CultureInfo.CurrentCulture,
Expand Down Expand Up @@ -413,7 +413,10 @@ private void LogReturnedToken(AdalResult result)
{
if (result.AccessToken != null)
{
var accessTokenHash = CoreCryptographyHelpers.CreateSha256Hash(result.AccessToken);
var accessTokenHash = PlatformProxyFactory
.GetPlatformProxy()
.CryptographyManager
.CreateSha256Hash(result.AccessToken);

{
var msg = string.Format(CultureInfo.CurrentCulture,
Expand Down
Expand Up @@ -29,10 +29,12 @@
using System.Collections.Generic;
using System.Globalization;
using System.Threading.Tasks;
using Microsoft.Identity.Core;
using Microsoft.Identity.Core.UI;
using Microsoft.Identity.Core.Cache;
using Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.Helpers;
using Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.OAuth2;
using Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.Platform;

namespace Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.Flows
{
Expand All @@ -58,7 +60,7 @@ internal class AcquireTokenInteractiveHandler : AcquireTokenHandlerBase
UserIdentifier userId, string extraQueryParameters, IWebUI webUI, string claims)
: base(requestData)
{
platformInformation.ValidateRedirectUri(redirectUri, RequestContext);
PlatformProxyFactory.GetPlatformProxy().ValidateRedirectUri(redirectUri, RequestContext);
this.redirectUri = redirectUri;

if (!string.IsNullOrWhiteSpace(this.redirectUri.Fragment))
Expand All @@ -68,14 +70,9 @@ internal class AcquireTokenInteractiveHandler : AcquireTokenHandlerBase

this.authorizationParameters = parameters;

this.redirectUriRequestParameter = platformInformation.GetRedirectUriAsString(this.redirectUri, RequestContext);
this.redirectUriRequestParameter = PlatformProxyFactory.GetPlatformProxy().GetRedirectUriAsString(this.redirectUri, RequestContext);

if (userId == null)
{
throw new ArgumentNullException("userId", AdalErrorMessage.SpecifyAnyUser);
}

this.userId = userId;
this.userId = userId ?? throw new ArgumentNullException(nameof(userId), AdalErrorMessage.SpecifyAnyUser);

if (!string.IsNullOrEmpty(extraQueryParameters) && extraQueryParameters[0] == '&')
{
Expand All @@ -97,6 +94,7 @@ internal class AcquireTokenInteractiveHandler : AcquireTokenHandlerBase
}
else
{
var platformInformation = new PlatformInformation();
this.LoadFromCache = (requestData.TokenCache != null && parameters != null && platformInformation.GetCacheLoadPolicy(parameters));
}

Expand Down Expand Up @@ -224,6 +222,7 @@ private DictionaryRequestParameters CreateAuthorizationRequest(string loginHint)

if (this.authorizationParameters != null)
{
var platformInformation = new PlatformInformation();
platformInformation.AddPromptBehaviorQueryParameter(this.authorizationParameters, authorizationRequestParameters);
}

Expand Down
Expand Up @@ -31,7 +31,6 @@
using Microsoft.Identity.Core;
using Microsoft.Identity.Core.Cache;
using Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.OAuth2;
using Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.Platform;

namespace Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.Flows
{
Expand All @@ -41,15 +40,13 @@ internal class AcquireTokenOnBehalfHandler : AcquireTokenHandlerBase

public AcquireTokenOnBehalfHandler(RequestData requestData, UserAssertion userAssertion)
: base(requestData)
{
if (userAssertion == null)
{
throw new ArgumentNullException("userAssertion");
}

this.userAssertion = userAssertion;
{
this.userAssertion = userAssertion ?? throw new ArgumentNullException(nameof(userAssertion));
this.DisplayableId = userAssertion.UserName;
CacheQueryData.AssertionHash = CoreCryptographyHelpers.CreateSha256Hash(userAssertion.Assertion);
CacheQueryData.AssertionHash = PlatformProxyFactory
.GetPlatformProxy()
.CryptographyManager
.CreateSha256Hash(userAssertion.Assertion);

RequestContext.Logger.Verbose(string.Format(CultureInfo.InvariantCulture,
"Username provided in user assertion - " + string.IsNullOrEmpty(DisplayableId)));
Expand Down
Expand Up @@ -30,6 +30,7 @@
using System.Text;
using System.Threading.Tasks;
using Microsoft.Identity.Core;
using Microsoft.Identity.Core.Http;
using Microsoft.Identity.Core.WsTrust;
using Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.Instance;
using Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.OAuth2;
Expand All @@ -41,11 +42,11 @@ namespace Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.Flows
/// </summary>
internal class AcquireTokenIWAHandler : AcquireTokenHandlerBase
{
private IntegratedWindowsAuthInput iwaInput;
private UserAssertion userAssertion;
private CommonNonInteractiveHandler commonNonInteractiveHandler;
private readonly IntegratedWindowsAuthInput _iwaInput;
private UserAssertion _userAssertion;
private readonly CommonNonInteractiveHandler _commonNonInteractiveHandler;

public AcquireTokenIWAHandler(RequestData requestData, IntegratedWindowsAuthInput iwaInput)
public AcquireTokenIWAHandler(IWsTrustWebRequestManager wsTrustWebRequestManager, RequestData requestData, IntegratedWindowsAuthInput iwaInput)
: base(requestData)
{
if (iwaInput == null)
Expand All @@ -59,24 +60,24 @@ public AcquireTokenIWAHandler(RequestData requestData, IntegratedWindowsAuthInpu
SupportADFS = true;
}

this.iwaInput = iwaInput;
this._iwaInput = iwaInput;
DisplayableId = iwaInput.UserName;

commonNonInteractiveHandler = new CommonNonInteractiveHandler(RequestContext, this.iwaInput);
_commonNonInteractiveHandler = new CommonNonInteractiveHandler(RequestContext, this._iwaInput, wsTrustWebRequestManager);
}

protected override async Task PreRunAsync()
{
await base.PreRunAsync().ConfigureAwait(false);

if (string.IsNullOrWhiteSpace(iwaInput.UserName))
if (string.IsNullOrWhiteSpace(_iwaInput.UserName))
{
string platformUsername = await commonNonInteractiveHandler.GetPlatformUserAsync()
string platformUsername = await _commonNonInteractiveHandler.GetPlatformUserAsync()
.ConfigureAwait(false);
iwaInput.UserName = platformUsername;
_iwaInput.UserName = platformUsername;
}

DisplayableId = iwaInput.UserName;
DisplayableId = _iwaInput.UserName;
}

protected override async Task PreTokenRequestAsync()
Expand All @@ -85,18 +86,18 @@ protected override async Task PreTokenRequestAsync()

if (!SupportADFS)
{
var userRealmResponse = await commonNonInteractiveHandler.QueryUserRealmDataAsync(Authenticator.UserRealmUriPrefix)
var userRealmResponse = await _commonNonInteractiveHandler.QueryUserRealmDataAsync(Authenticator.UserRealmUriPrefix)
.ConfigureAwait(false);

if (string.Equals(userRealmResponse.AccountType, "federated", StringComparison.OrdinalIgnoreCase))
{
WsTrustResponse wsTrustResponse = await commonNonInteractiveHandler.PerformWsTrustMexExchangeAsync(
WsTrustResponse wsTrustResponse = await _commonNonInteractiveHandler.PerformWsTrustMexExchangeAsync(
userRealmResponse.FederationMetadataUrl,
userRealmResponse.CloudAudienceUrn,
UserAuthType.IntegratedAuth).ConfigureAwait(false);

// We assume that if the response token type is not SAML 1.1, it is SAML 2
userAssertion = new UserAssertion(wsTrustResponse.Token, (wsTrustResponse.TokenType == WsTrustResponse.Saml1Assertion) ? OAuthGrantType.Saml11Bearer : OAuthGrantType.Saml20Bearer);
_userAssertion = new UserAssertion(wsTrustResponse.Token, (wsTrustResponse.TokenType == WsTrustResponse.Saml1Assertion) ? OAuthGrantType.Saml11Bearer : OAuthGrantType.Saml20Bearer);
}
else
{
Expand All @@ -107,10 +108,10 @@ protected override async Task PreTokenRequestAsync()

protected override void AddAditionalRequestParameters(DictionaryRequestParameters requestParameters)
{
Debug.Assert(userAssertion != null, "Expected the user assertion to have been created by PreTokenRequestAsync");
Debug.Assert(_userAssertion != null, "Expected the user assertion to have been created by PreTokenRequestAsync");

requestParameters[OAuthParameter.GrantType] = userAssertion.AssertionType;
requestParameters[OAuthParameter.Assertion] = Convert.ToBase64String(Encoding.UTF8.GetBytes(userAssertion.Assertion));
requestParameters[OAuthParameter.GrantType] = _userAssertion.AssertionType;
requestParameters[OAuthParameter.Assertion] = Convert.ToBase64String(Encoding.UTF8.GetBytes(_userAssertion.Assertion));

// To request id_token in response
requestParameters[OAuthParameter.Scope] = OAuthValue.ScopeOpenId;
Expand Down
Expand Up @@ -39,9 +39,9 @@ internal class AcquireTokenUsernamePasswordHandler : AcquireTokenHandlerBase
{
private readonly UsernamePasswordInput _userPasswordInput;
private UserAssertion _userAssertion;
private CommonNonInteractiveHandler _commonNonInteractiveHandler;
private readonly CommonNonInteractiveHandler _commonNonInteractiveHandler;

public AcquireTokenUsernamePasswordHandler(RequestData requestData, UsernamePasswordInput userPasswordInput)
public AcquireTokenUsernamePasswordHandler(IWsTrustWebRequestManager wsTrustWebRequestManager, RequestData requestData, UsernamePasswordInput userPasswordInput)
: base(requestData)
{
// We enable ADFS support only when it makes sense to do so
Expand All @@ -51,7 +51,7 @@ public AcquireTokenUsernamePasswordHandler(RequestData requestData, UsernamePass
}

_userPasswordInput = userPasswordInput ?? throw new ArgumentNullException(nameof(userPasswordInput));
_commonNonInteractiveHandler = new CommonNonInteractiveHandler(RequestContext, _userPasswordInput);
_commonNonInteractiveHandler = new CommonNonInteractiveHandler(RequestContext, _userPasswordInput, wsTrustWebRequestManager);
DisplayableId = userPasswordInput.UserName;
}

Expand Down
Expand Up @@ -76,7 +76,7 @@ internal static class AdalIdHelper

var parameters = new Dictionary<string, string>();

parameters[AdalIdParameter.Product] = new PlatformInformation().GetProductName();
parameters[AdalIdParameter.Product] = PlatformProxyFactory.GetPlatformProxy().GetProductName();
parameters[AdalIdParameter.Version] = GetAdalVersion();

var processorInfo = platformProxy.GetProcessorArchitecture();
Expand Down Expand Up @@ -112,16 +112,5 @@ public static string GetAdalVersion()

return null;
}

public static string GetAssemblyFileVersion()
{
return new PlatformInformation().GetAssemblyFileVersionAttribute();
}

public static string GetAssemblyInformationalVersion()
{
AssemblyInformationalVersionAttribute attribute = typeof(AdalIdHelper).GetTypeInfo().Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>();
return (attribute != null) ? attribute.InformationalVersion : string.Empty;
}
}
}

0 comments on commit 93d88f3

Please sign in to comment.