public void ValidateGetPlatformProxyPerformance() { using (new PerformanceValidator(200, "GetPlatformProxy")) { PlatformProxyFactory.CreatePlatformProxy(null); } }
public static IServiceBundle CreateServiceBundleWithCustomHttpManager( IHttpManager httpManager, TelemetryCallback telemetryCallback = null, LogCallback logCallback = null, string authority = ClientApplicationBase.DefaultAuthority, bool isExtendedTokenLifetimeEnabled = false, bool enablePiiLogging = false, string clientId = TestConstants.ClientId, bool clearCaches = true, bool validateAuthority = true, bool isLegacyCacheEnabled = true) { var appConfig = new ApplicationConfiguration() { ClientId = clientId, HttpManager = httpManager, RedirectUri = PlatformProxyFactory.CreatePlatformProxy(null).GetDefaultRedirectUri(clientId), TelemetryCallback = telemetryCallback, LoggingCallback = logCallback, LogLevel = LogLevel.Verbose, EnablePiiLogging = enablePiiLogging, IsExtendedTokenLifetimeEnabled = isExtendedTokenLifetimeEnabled, AuthorityInfo = AuthorityInfo.FromAuthorityUri(authority, validateAuthority), LegacyCacheCompatibilityEnabled = isLegacyCacheEnabled }; return(new ServiceBundle(appConfig, clearCaches)); }
internal MsalLogger( Guid correlationId, string clientName, string clientVersion, LogLevel logLevel, bool enablePiiLogging, bool isDefaultPlatformLoggingEnabled, LogCallback loggingCallback) { _correlationId = correlationId; PiiLoggingEnabled = enablePiiLogging; _loggingCallback = loggingCallback; _minLogLevel = logLevel; _isDefaultPlatformLoggingEnabled = isDefaultPlatformLoggingEnabled; _platformLogger = PlatformProxyFactory.CreatePlatformProxy(null).PlatformLogger; ClientName = clientName ?? string.Empty; ClientVersion = clientVersion ?? string.Empty; ClientInformation = string.Empty; if (!string.IsNullOrEmpty(clientName) && !ApplicationConfiguration.DefaultClientName.Equals(clientName)) { // space is intentional for formatting of the message if (string.IsNullOrEmpty(clientVersion)) { ClientInformation = string.Format(CultureInfo.InvariantCulture, " ({0})", clientName); } else { ClientInformation = string.Format(CultureInfo.InvariantCulture, " ({0}: {1})", clientName, clientVersion); } } }
internal TokenCache(IServiceBundle serviceBundle, bool isApplicationTokenCache) { var proxy = serviceBundle?.PlatformProxy ?? PlatformProxyFactory.CreatePlatformProxy(null); _accessor = proxy.CreateTokenCacheAccessor(); _featureFlags = proxy.GetFeatureFlags(); _defaultTokenCacheBlobStorage = proxy.CreateTokenCacheBlobStorage(); if (_defaultTokenCacheBlobStorage != null) { BeforeAccess = _defaultTokenCacheBlobStorage.OnBeforeAccess; AfterAccess = _defaultTokenCacheBlobStorage.OnAfterAccess; BeforeWrite = _defaultTokenCacheBlobStorage.OnBeforeWrite; AsyncBeforeAccess = null; AsyncAfterAccess = null; AsyncBeforeWrite = null; } LegacyCachePersistence = proxy.CreateLegacyCachePersistence(); #if iOS SetIosKeychainSecurityGroup(serviceBundle.Config.IosKeychainSecurityGroup); #endif // iOS IsAppTokenCache = isApplicationTokenCache; // Must happen last, this code can access things like _accessor and such above. ServiceBundle = serviceBundle; }
public static void ConfigureMockWebUI(MockWebUI webUi) { IWebUIFactory mockFactory = Substitute.For <IWebUIFactory>(); mockFactory.CreateAuthenticationDialog(Arg.Any <CoreUIParent>(), Arg.Any <RequestContext>()).Returns(webUi); PlatformProxyFactory.GetPlatformProxy().SetWebUiFactory(mockFactory); }
/// <summary> /// Use Microsoft Edge Chromium to navigate to the given URI. Requires the browser to be installed. /// On Linux, uses the default system browser instead, as Edge is not available. /// </summary> public static async Task OpenWithChromeEdgeBrowserAsync(Uri uri) { if (uri == null) { throw new ArgumentNullException(nameof(uri)); } string url = uri.AbsoluteUri; if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { url = url.Replace("&", "^&"); Process.Start(new ProcessStartInfo("cmd", $"/c start msedge {url}") { CreateNoWindow = true }); } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { var proxy = PlatformProxyFactory.CreatePlatformProxy(new NullLogger()); await proxy.StartDefaultOsBrowserAsync(url).ConfigureAwait(false); } else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { Process.Start("msedge", url); } else { throw new PlatformNotSupportedException(RuntimeInformation.OSDescription); } }
/// <summary> /// Use Microsoft Edge to navigate to the given uri. On non-windows platforms it uses /// whatever browser is the default /// </summary> public static async Task OpenWithEdgeBrowserAsync(Uri uri) { if (uri == null) { throw new ArgumentNullException(nameof(uri)); } string url = uri.AbsoluteUri; #if DESKTOP url = url.Replace("&", "^&"); Process.Start(new ProcessStartInfo("cmd", $"/c start microsoft-edge:{url}") { CreateNoWindow = true }); await Task.FromResult(0).ConfigureAwait(false); #else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { url = url.Replace("&", "^&"); Process.Start(new ProcessStartInfo("cmd", $"/c start microsoft-edge:{url}") { CreateNoWindow = true }); } else { var proxy = PlatformProxyFactory.CreatePlatformProxy(new NullLogger()); await proxy.StartDefaultOsBrowserAsync(url).ConfigureAwait(false); } #endif }
internal TokenCache(IServiceBundle serviceBundle, bool isApplicationTokenCache, ICacheSerializationProvider optionalDefaultSerializer = null) { if (serviceBundle == null) { throw new ArgumentNullException(nameof(serviceBundle)); } // useRealSemaphore= false for MyApps and potentially for all apps when using non-singleton MSAL _semaphoreSlim = new OptionalSemaphoreSlim(useRealSemaphore: serviceBundle.Config.CacheSynchronizationEnabled); var proxy = serviceBundle?.PlatformProxy ?? PlatformProxyFactory.CreatePlatformProxy(null); Accessor = proxy.CreateTokenCacheAccessor(serviceBundle.Config.AccessorOptions, isApplicationTokenCache); _featureFlags = proxy.GetFeatureFlags(); UsesDefaultSerialization = optionalDefaultSerializer != null; optionalDefaultSerializer?.Initialize(this); LegacyCachePersistence = proxy.CreateLegacyCachePersistence(); #if iOS SetIosKeychainSecurityGroup(serviceBundle.Config.IosKeychainSecurityGroup); #endif // iOS IsAppTokenCache = isApplicationTokenCache; // Must happen last, this code can access things like _accessor and such above. ServiceBundle = serviceBundle; }
public void PlatformProxy_HttpClient_DoesNotSetGlobalProperties() { // Arrange int originalDnsTimeout = ServicePointManager.DnsRefreshTimeout; int originalConnLimit = ServicePointManager.DefaultConnectionLimit; try { int newDnsTimeout = 1001; int newConnLimit = 42; ServicePointManager.DnsRefreshTimeout = newDnsTimeout; ServicePointManager.DefaultConnectionLimit = newConnLimit; // Act var factory = PlatformProxyFactory.CreatePlatformProxy(null) .CreateDefaultHttpClientFactory(); _ = factory.GetHttpClient(); // Assert - the factory does not override these global properties Assert.AreEqual(newDnsTimeout, ServicePointManager.DnsRefreshTimeout); Assert.AreEqual(newConnLimit, ServicePointManager.DefaultConnectionLimit); } finally { ServicePointManager.DnsRefreshTimeout = originalDnsTimeout; ServicePointManager.DefaultConnectionLimit = originalConnLimit; } }
public void TestConstructor_WithWhitespaceRedirectUri() { var pca = PublicClientApplicationBuilder.Create(TestConstants.ClientId) .WithRedirectUri(" ") .Build(); Assert.AreEqual(PlatformProxyFactory.CreatePlatformProxy(null).GetDefaultRedirectUri(TestConstants.ClientId), pca.AppConfig.RedirectUri); }
public void PlatformProxyFactoryCachesTheProxy() { // Act var proxy1 = PlatformProxyFactory.GetPlatformProxy(); var proxy2 = PlatformProxyFactory.GetPlatformProxy(); // Assert Assert.IsTrue(proxy1 == proxy2); }
public void PlatformProxyFactoryDoesNotCacheTheProxy() { // Act var proxy1 = PlatformProxyFactory.CreatePlatformProxy(null); var proxy2 = PlatformProxyFactory.CreatePlatformProxy(null); // Assert Assert.IsFalse(proxy1 == proxy2); }
public void ExpiredTokenRefreshFlowTest() { using (var httpManager = new MockHttpManager()) { var serviceBundle = ServiceBundle.CreateWithCustomHttpManager(httpManager); var aadInstanceDiscovery = new AadInstanceDiscovery(httpManager, new TelemetryManager()); Authority authority = Authority.CreateAuthority(serviceBundle, MsalTestConstants.AuthorityHomeTenant, false); TokenCache cache = new TokenCache() { ClientId = MsalTestConstants.ClientId, ServiceBundle = serviceBundle }; _tokenCacheHelper.PopulateCache(cache.TokenCacheAccessor); AuthenticationRequestParameters parameters = new AuthenticationRequestParameters() { Authority = authority, ClientId = MsalTestConstants.ClientId, Scope = MsalTestConstants.Scope, TokenCache = cache, RequestContext = new RequestContext(null, new MsalLogger(Guid.Empty, null)), Account = new Account(MsalTestConstants.UserIdentifier, MsalTestConstants.DisplayableId, null) }; // set access tokens as expired foreach (var atCacheItemStr in cache.GetAllAccessTokenCacheItems(new RequestContext(null, new MsalLogger(Guid.NewGuid(), null)))) { MsalAccessTokenCacheItem accessItem = JsonHelper.DeserializeFromJson <MsalAccessTokenCacheItem>(atCacheItemStr); accessItem.ExpiresOnUnixTimestamp = ((long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds).ToString(CultureInfo.InvariantCulture); cache.AddAccessTokenCacheItem(accessItem); } TestCommon.MockInstanceDiscoveryAndOpenIdRequest(httpManager); httpManager.AddMockHandler(new MockHttpMessageHandler() { Method = HttpMethod.Post, ResponseMessage = MockHelpers.CreateSuccessTokenResponseMessage() }); var crypto = PlatformProxyFactory.GetPlatformProxy().CryptographyManager; SilentRequest request = new SilentRequest( serviceBundle, parameters, ApiEvent.ApiIds.None, false); Task <AuthenticationResult> task = request.RunAsync(CancellationToken.None); AuthenticationResult result = task.Result; Assert.IsNotNull(result); Assert.AreEqual("some-access-token", result.AccessToken); Assert.AreEqual(MsalTestConstants.Scope.AsSingleString(), result.Scopes.AsSingleString()); } }
public void PlatformProxy_HttpClient_NetCore() { // Arrange var factory = PlatformProxyFactory.CreatePlatformProxy(null) .CreateDefaultHttpClientFactory(); // Assert Assert.IsTrue(factory is Client.Platforms.netcore.NetCoreHttpClientFactory); }
public string ToSafeFilename(string data) { string normalizedData = NormalizeKey(data); byte[] hash = PlatformProxyFactory.GetPlatformProxy().CryptographyManager.CreateSha256HashBytes(normalizedData); var sizedHash = new byte[10]; Array.Copy(hash, sizedHash, 10); return(Base32Hex.ToBase32String(sizedHash)); }
private static void ValidateExceptionProductInformation(MsalException exception) { string exceptionString = exception.ToString(); string msalProductName = PlatformProxyFactory.CreatePlatformProxy(null).GetProductName(); string msalVersion = MsalIdHelper.GetMsalVersion(); Assert.IsTrue(exceptionString.Contains(msalProductName), "Exception should contain the msalProductName"); Assert.IsTrue(exceptionString.Contains(msalVersion), "Exception should contain the msalVersion"); }
internal MsalLogger(Guid correlationId, string component) { CorrelationId = correlationId; _platformLogger = PlatformProxyFactory.GetPlatformProxy().PlatformLogger; Component = string.Empty; if (!string.IsNullOrEmpty(component)) { //space is intentional for formatting of the message Component = string.Format(CultureInfo.InvariantCulture, " ({0})", component); } }
/// <summary> /// Gets a key that is smaller than 255 characters, which is a limitation for /// UWP storage. This is done by hashing the scopes and env. /// </summary> /// <remarks> /// accountId - two guids plus separator - 73 chars /// "accesstoken" string - 11 chars /// env - ussually loging.microsoft.net - 20 chars /// clientid - a guid - 36 chars /// tenantid - a guid - 36 chars /// scopes - a sha256 string - 44 chars /// delimiters - 4 chars /// total: 224 chars /// </remarks> public string GetUWPFixedSizeKey() { var crypto = PlatformProxyFactory.GetPlatformProxy().CryptographyManager; return(MsalCacheCommon.GetCredentialKey( _homeAccountId, _environment, MsalCacheCommon.AccessToken, _clientId, _tenantId, crypto.CreateSha256Hash(_normalizedScopes))); // can't use scopes and env because they are of variable length }
internal PublicClientApplication(IServiceBundle serviceBundle, string clientId, string authority) : base( clientId, authority, PlatformProxyFactory.GetPlatformProxy().GetDefaultRedirectUri(clientId), true, serviceBundle) { UserTokenCache = new TokenCache() { ClientId = clientId }; }
private void ValidateMethodPerformance(long maxMilliseconds, string name, Action <IPlatformProxy> action) { var platformProxy = PlatformProxyFactory.CreatePlatformProxy(null); // Call it once to pre-load it. We're not worried about the time it takes to call it // the first time, we're worried about subsequent calls. action(platformProxy); using (new PerformanceValidator(maxMilliseconds, name)) { action(platformProxy); } }
public void SignWithCertificate() { // Tests the cryptography libraries used by MSAL to sign with certificates var cert = new X509Certificate2( ResourceHelper.GetTestResourceRelativePath("testCert.crtfile"), "passw0rd!"); var crypto = PlatformProxyFactory.GetPlatformProxy().CryptographyManager; byte[] result = crypto.SignWithCertificate("TEST", cert); string value = Base64UrlHelpers.Encode(result); Assert.IsNotNull(value); Assert.AreEqual("MrknKHbOAVu2iuLHMFSk2SK773H1ysxaAjAPcTXYSfH4P2fUfvzP6aIb9MkBknjoE_aBYtTnQ7jOAvyQETvogdeSH7pRDPhCk2aX_8VIQw0bjo_zBZj5yJYVWQDLIu8XvbuzIGEvVaXKz4jJ1nYM6toun4tM74rEHvwa0ferafmqHWOd5puPhlKH1VVK2RPuNOoKNLWBprVBaAQVJVFOdRcd3iR0INBHykxtOsG0pgo0Q2uQBlKP7KQb7Ox8i_sw-M21BuUzdIdGs_oeUYh0B8s-eIGf34JmHRWMwWCnRWzZgY9YuIjRoaWNqlWYb8ASjKOxzvk99x8eFEYKOjgAcA", value); }
public DefaultEvent(string clientId, IDictionary <string, int> eventCount) : base((string)(EventNamePrefix + "default_event")) { var platformProxy = PlatformProxyFactory.GetPlatformProxy(); this[EventNamePrefix + "client_id"] = clientId; this[EventNamePrefix + "sdk_platform"] = platformProxy.GetProductName()?.ToLowerInvariant(); this[EventNamePrefix + "sdk_version"] = MsalIdHelper.GetMsalVersion(); this[EventNamePrefix + "application_name"] = HashPersonalIdentifier(platformProxy.GetCallingApplicationName()?.ToLowerInvariant()); this[EventNamePrefix + "application_version"] = HashPersonalIdentifier(platformProxy.GetCallingApplicationVersion()?.ToLowerInvariant()); this[EventNamePrefix + "device_id"] = HashPersonalIdentifier(platformProxy.GetDeviceId()?.ToLowerInvariant()); this[EventNamePrefix + "ui_event_count"] = GetEventCount(EventNamePrefix + "ui_event", eventCount); this[EventNamePrefix + "http_event_count"] = GetEventCount(EventNamePrefix + "http_event", eventCount); this[EventNamePrefix + "cache_event_count"] = GetEventCount(EventNamePrefix + "cache_event", eventCount); }
public void PlatformProxy_HttpClient_NetCore() { // Arrange var factory = PlatformProxyFactory.CreatePlatformProxy(null) .CreateDefaultHttpClientFactory(); // Act var client1 = factory.GetHttpClient(); var client2 = factory.GetHttpClient(); // Assert Assert.IsTrue(factory is SimpleHttpClientFactory); Assert.AreSame(client1, client2, "On NetDesktop and NetCore, the HttpClient should be static"); }
internal ServiceBundle( ApplicationConfiguration config) { Config = config; DefaultLogger = new AuthLogger( config.LogLevel, config.EnablePiiLogging, config.IsDefaultPlatformLoggingEnabled, config.LoggingCallback); PlatformProxy = PlatformProxyFactory.CreatePlatformProxy(DefaultLogger); HttpManager = config.HttpManager ?? new HttpManager(config.HttpClientFactory); }
/// <inheritdoc /> internal override void Validate() { base.Validate(); if (string.IsNullOrWhiteSpace(Config.RedirectUri)) { Config.RedirectUri = PlatformProxyFactory.CreatePlatformProxy(null) .GetDefaultRedirectUri(Config.ClientId, Config.UseRecommendedDefaultRedirectUri); } if (!Uri.TryCreate(Config.RedirectUri, UriKind.Absolute, out Uri uriResult)) { throw new InvalidOperationException(MsalErrorMessage.InvalidRedirectUriReceived(Config.RedirectUri)); } }
public void SilentRefreshFailedNoCacheItemFoundTest() { using (var httpManager = new MockHttpManager()) { var serviceBundle = ServiceBundle.CreateWithCustomHttpManager(httpManager); var aadInstanceDiscovery = new AadInstanceDiscovery(httpManager, new TelemetryManager()); var authority = Authority.CreateAuthority(serviceBundle, MsalTestConstants.AuthorityHomeTenant, false); _cache = new TokenCache() { ClientId = MsalTestConstants.ClientId, ServiceBundle = serviceBundle }; httpManager.AddInstanceDiscoveryMockHandler(); var parameters = new AuthenticationRequestParameters() { Authority = authority, ClientId = MsalTestConstants.ClientId, Scope = ScopeHelper.CreateSortedSetFromEnumerable( new[] { "some-scope1", "some-scope2" }), TokenCache = _cache, Account = new Account(MsalTestConstants.UserIdentifier, MsalTestConstants.DisplayableId, null), RequestContext = new RequestContext(null, new MsalLogger(Guid.NewGuid(), null)) }; var crypto = PlatformProxyFactory.GetPlatformProxy().CryptographyManager; var telemetryManager = new TelemetryManager(); try { var request = new SilentRequest(serviceBundle, parameters, ApiEvent.ApiIds.None, false); Task <AuthenticationResult> task = request.RunAsync(CancellationToken.None); var authenticationResult = task.Result; Assert.Fail("MsalUiRequiredException should be thrown here"); } catch (AggregateException ae) { var exc = ae.InnerException as MsalUiRequiredException; Assert.IsNotNull(exc, "Actual exception type is " + ae.InnerException.GetType()); Assert.AreEqual(MsalUiRequiredException.NoTokensFoundError, exc.ErrorCode); } } }
internal ServiceBundle( ApplicationConfiguration config, bool shouldClearCaches = false) { Config = config; ApplicationLogger = new MsalLogger( Guid.Empty, config.ClientName, config.ClientVersion, config.LogLevel, config.EnablePiiLogging, config.IsDefaultPlatformLoggingEnabled, config.LoggingCallback); PlatformProxy = config.PlatformProxy ?? PlatformProxyFactory.CreatePlatformProxy(ApplicationLogger); HttpManager = config.HttpManager ?? new HttpManager( config.HttpClientFactory ?? PlatformProxy.CreateDefaultHttpClientFactory()); HttpTelemetryManager = new HttpTelemetryManager(); if (config.TelemetryConfig != null) { // This can return null if the device isn't sampled in. There's no need for processing MATS events if we're not going to send them. Mats = TelemetryClient.CreateMats(config, PlatformProxy, config.TelemetryConfig); MatsTelemetryManager = Mats?.TelemetryManager ?? new TelemetryManager(config, PlatformProxy, config.TelemetryCallback); } else { MatsTelemetryManager = new TelemetryManager(config, PlatformProxy, config.TelemetryCallback); } InstanceDiscoveryManager = new InstanceDiscoveryManager( HttpManager, shouldClearCaches, config.CustomInstanceDiscoveryMetadata, config.CustomInstanceDiscoveryMetadataUri); WsTrustWebRequestManager = new WsTrustWebRequestManager(HttpManager); ThrottlingManager = SingletonThrottlingManager.GetInstance(); DeviceAuthManager = config.DeviceAuthManagerForTest ?? PlatformProxy.CreateDeviceAuthManager(); if (shouldClearCaches) { AuthorityManager.ClearValidationCache(); } }
public void PlatformProxyFactoryReturnsInstances() { // Arrange var proxy = PlatformProxyFactory.CreatePlatformProxy(null); // Act and Assert Assert.AreNotSame( proxy.CreateLegacyCachePersistence(), proxy.CreateLegacyCachePersistence()); Assert.AreNotSame( proxy.CreateTokenCacheAccessor(), proxy.CreateTokenCacheAccessor()); Assert.AreSame( proxy.CryptographyManager, proxy.CryptographyManager); }
/// <summary> /// Constructor of a UserAssertion specifying the assertionType in addition to the assertion /// </summary> /// <param name="assertion">Assertion representing the user.</param> /// <param name="assertionType">Type of the assertion representing the user. Accepted types are currently: /// <list type="bullet"> /// <item>urn:ietf:params:oauth:grant-type:jwt-bearer<term></term><description>JWT bearer token. Passing this is equivalent to using /// the other (simpler) constructor</description></item> /// <item>urn:ietf:params:oauth:grant-type:saml1_1-bearer<term></term><description>SAML 1.1 bearer token</description></item> /// <item>urn:ietf:params:oauth:grant-type:jwt-bearer<term></term><description>SAML 2 bearer token</description></item> /// </list></param> public UserAssertion(string assertion, string assertionType) { if (string.IsNullOrWhiteSpace(assertion)) { throw new ArgumentNullException(nameof(assertion)); } if (string.IsNullOrWhiteSpace(assertionType)) { throw new ArgumentNullException(nameof(assertionType)); } var crypto = PlatformProxyFactory.GetPlatformProxy().CryptographyManager; AssertionType = assertionType; Assertion = assertion; AssertionHash = crypto.CreateBase64UrlEncodedSha256Hash(Assertion); }
public static void SetCacheOptions(this ITokenCache tokenCache, CacheOptions options) { ValidatePlatform(); TokenCache cache = (TokenCache)tokenCache; ITokenCacheInternal tokenCacheInternal = (ITokenCacheInternal)tokenCache; cache.ServiceBundle.Config.AccessorOptions = options; if (tokenCacheInternal.IsAppSubscribedToSerializationEvents()) { throw new MsalClientException( MsalError.StaticCacheWithExternalSerialization, MsalErrorMessage.StaticCacheWithExternalSerialization); } var proxy = cache.ServiceBundle?.PlatformProxy ?? PlatformProxyFactory.CreatePlatformProxy(null); cache.Accessor = proxy.CreateTokenCacheAccessor(options, tokenCacheInternal.IsApplicationCache); }