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);
        }
コード例 #2
0
 public void ValidateGetPlatformProxyPerformance()
 {
     using (new PerformanceValidator(50, "GetPlatformProxy"))
     {
         PlatformProxyFactory.GetPlatformProxy();
     }
 }
コード例 #3
0
        private async Task RunTestForUserAsync(LabResponse labResponse)
        {
            Action <IWebDriver> seleniumLogic = (driver) =>
            {
                Trace.WriteLine("Starting Selenium automation");
                driver.PerformLogin(labResponse.User);
            };

            SeleniumWebUIFactory webUIFactory = new SeleniumWebUIFactory(seleniumLogic, _seleniumTimeout);

            PlatformProxyFactory.GetPlatformProxy().SetWebUiFactory(webUIFactory);

            PublicClientApplication pca = new PublicClientApplication(labResponse.AppId);

            // tests need to use http://localhost:port so that we can capture the AT
            pca.RedirectUri = SeleniumWebUIFactory.FindFreeLocalhostRedirectUri();
            AuthenticationResult result = null;

            // Act
            result = await pca.AcquireTokenAsync(new[] { "user.read" }).ConfigureAwait(false);


            // Assert
            Assert.IsFalse(string.IsNullOrWhiteSpace(result.AccessToken));
        }
        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 PlatformProxyFactoryCachesTheProxy()
        {
            // Act
            var proxy1 = PlatformProxyFactory.GetPlatformProxy();
            var proxy2 = PlatformProxyFactory.GetPlatformProxy();

            // Assert
            Assert.IsTrue(proxy1 == proxy2);
        }
コード例 #6
0
        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));
        }
コード例 #7
0
 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);
     }
 }
コード例 #8
0
        /// <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
        }
コード例 #9
0
        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);
        }
コード例 #10
0
 internal PublicClientApplication(IServiceBundle serviceBundle, string clientId, string authority)
     : base(
         clientId,
         authority,
         PlatformProxyFactory.GetPlatformProxy().GetDefaultRedirectUri(clientId),
         true,
         serviceBundle)
 {
     UserTokenCache = new TokenCache()
     {
         ClientId = clientId
     };
 }
コード例 #11
0
        private void ValidateMethodPerformance(long maxMilliseconds, string name, Action <IPlatformProxy> action)
        {
            var platformProxy = PlatformProxyFactory.GetPlatformProxy();

            // 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 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 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);
                }
            }
        }
        public void PlatformProxyFactoryReturnsInstances()
        {
            // Arrange
            var proxy = PlatformProxyFactory.GetPlatformProxy();

            // 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);
        }
コード例 #16
0
        internal PublicClientApplication(
            IHttpManager httpManager,
            IStorageManager storageManager,
            IBrowserFactory browserFactory,
            IGuidService guidService,
            ITelemetryManager telemetryManager,
            EnvironmentMetadata environmentMetadata,
            MsalClientConfiguration msalClientConfiguration)
        {
            _platformProxy = PlatformProxyFactory.GetPlatformProxy();

            _httpManager             = httpManager ?? new HttpManager(new HttpClientFactory(), msalClientConfiguration);
            _storageManager          = storageManager ?? _platformProxy.CreateStorageManager();
            _browserFactory          = browserFactory ?? _platformProxy.CreateBrowserFactory();
            _guidService             = guidService ?? new GuidService();
            _telemetryManager        = telemetryManager ?? new TelemetryManager(msalClientConfiguration);
            _environmentMetadata     = environmentMetadata ?? new EnvironmentMetadata();
            _msalClientConfiguration = msalClientConfiguration;
        }
コード例 #17
0
        private static void ValidateCommonQueryParams(
            Dictionary <string, string> qp,
            string redirectUri = MsalTestConstants.RedirectUri)
        {
            Assert.IsNotNull(qp);

            Assert.IsTrue(qp.ContainsKey("client-request-id"));
            Assert.AreEqual(MsalTestConstants.ClientId, qp["client_id"]);
            Assert.AreEqual("code", qp["response_type"]);
            Assert.AreEqual(redirectUri, qp["redirect_uri"]);
            Assert.AreEqual(MsalTestConstants.DisplayableId, qp["login_hint"]);
            Assert.AreEqual(UIBehavior.SelectAccount.PromptValue, qp["prompt"]);
            Assert.AreEqual(PlatformProxyFactory.GetPlatformProxy().GetProductName(), qp["x-client-sku"]);
            Assert.IsFalse(string.IsNullOrEmpty(qp["x-client-ver"]));
            Assert.IsFalse(string.IsNullOrEmpty(qp["x-client-os"]));

#if !NET_CORE
            Assert.IsFalse(string.IsNullOrEmpty(qp["x-client-cpu"]));
#endif
        }
        public void GetEnvRetrievesAValue()
        {
            try
            {
                // Arrange
                Environment.SetEnvironmentVariable("proxy_foo", "bar");

                var proxy = PlatformProxyFactory.GetPlatformProxy();

                // Act
                string actualValue      = proxy.GetEnvironmentVariable("proxy_foo");
                string actualEmptyValue = proxy.GetEnvironmentVariable("no_such_env_var_exists");


                // Assert
                Assert.AreEqual("bar", actualValue);
                Assert.IsNull(actualEmptyValue);
            }
            finally
            {
                Environment.SetEnvironmentVariable("proxy_foo", "");
            }
        }
        public void ConstructorTests()
        {
            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);
                var cache = new TokenCache()
                {
                    ClientId      = MsalTestConstants.ClientId,
                    ServiceBundle = serviceBundle
                };
                var parameters = new AuthenticationRequestParameters()
                {
                    Authority      = authority,
                    ClientId       = MsalTestConstants.ClientId,
                    Scope          = MsalTestConstants.Scope,
                    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();

                var request = new SilentRequest(serviceBundle, parameters, ApiEvent.ApiIds.None, false);
                Assert.IsNotNull(request);

                parameters.Account = new Account(MsalTestConstants.UserIdentifier, MsalTestConstants.DisplayableId, null);

                request = new SilentRequest(serviceBundle, parameters, ApiEvent.ApiIds.None, false);
                Assert.IsNotNull(request);

                request = new SilentRequest(serviceBundle, parameters, ApiEvent.ApiIds.None, false);
                Assert.IsNotNull(request);
            }
        }
 public void GetEnvThrowsArgNullEx()
 {
     AssertException.Throws <ArgumentNullException>(
         () =>
         PlatformProxyFactory.GetPlatformProxy().GetEnvironmentVariable(""));
 }
コード例 #21
0
        internal byte[] Sign(string message)
        {
            var crypto = PlatformProxyFactory.GetPlatformProxy().CryptographyManager;

            return(crypto.SignWithCertificate(message, Certificate));
        }
コード例 #22
0
 public StorageManager(IStorageWorker storageWorker, IAdalLegacyCacheManager adalLegacyCacheManager = null)
 {
     _storageWorker         = storageWorker;
     AdalLegacyCacheManager = adalLegacyCacheManager ?? new AdalLegacyCacheManager(PlatformProxyFactory.GetPlatformProxy().CreateLegacyCachePersistence());
 }
コード例 #23
0
        public string HashPersonalIdentifier(string valueToHash)
        {
            var crypto = PlatformProxyFactory.GetPlatformProxy().CryptographyManager;

            return(crypto.CreateBase64UrlEncodedSha256Hash(valueToHash));
        }
コード例 #24
0
 internal byte[] Sign(string message)
 {
     return(PlatformProxyFactory.GetPlatformProxy().GetCryptographyUtils()
            .SignWithCertificate(message, Certificate));
 }