Example #1
0
        public void GetAccessTokenExpiryInRangeTest()
        {
            cache = new TokenCache()
            {
                ClientId = TestConstants.ClientId
            };

            AccessTokenCacheItem atItem = new AccessTokenCacheItem()
            {
                Authority              = TestConstants.AuthorityHomeTenant,
                ClientId               = TestConstants.ClientId,
                ScopeSet               = TestConstants.Scope,
                RawIdToken             = MockHelpers.CreateIdToken(TestConstants.UniqueId, TestConstants.DisplayableId),
                TokenType              = "Bearer",
                ExpiresOnUnixTimestamp = MsalHelpers.DateTimeToUnixTimestamp(DateTime.UtcNow + TimeSpan.FromMinutes(4))
            };

            atItem.AccessToken = atItem.GetAccessTokenItemKey().ToString();
            cache.TokenCacheAccessor.AccessTokenCacheDictionary[atItem.GetAccessTokenItemKey().ToString()] =
                JsonHelper.SerializeToJson(atItem);

            Assert.IsNull(cache.FindAccessToken(new AuthenticationRequestParameters()
            {
                RequestContext = new RequestContext(Guid.Empty, null),
                ClientId       = TestConstants.ClientId,
                Authority      = Authority.CreateAuthority(TestConstants.AuthorityHomeTenant, false),
                Scope          = TestConstants.Scope,
                User           =
                    new User()
                {
                    DisplayableId = TestConstants.DisplayableId,
                    Identifier    = TestConstants.UserIdentifier
                }
            }));
        }
Example #2
0
        public InteractiveRequest(AuthenticationRequestParameters authenticationRequestParameters,
                                  IEnumerable <string> extraScopesToConsent, string loginHint,
                                  UIBehavior UIBehavior, IWebUI webUI)
            : base(authenticationRequestParameters)
        {
            PlatformPlugin.PlatformInformation.ValidateRedirectUri(authenticationRequestParameters.RedirectUri,
                                                                   authenticationRequestParameters.RequestContext);
            if (!string.IsNullOrWhiteSpace(authenticationRequestParameters.RedirectUri.Fragment))
            {
                throw new ArgumentException(MsalErrorMessage.RedirectUriContainsFragment, nameof(authenticationRequestParameters.RedirectUri));
            }

            _extraScopesToConsent = new SortedSet <string>();
            if (!MsalHelpers.IsNullOrEmpty(extraScopesToConsent))
            {
                _extraScopesToConsent = extraScopesToConsent.CreateSetFromEnumerable();
            }

            ValidateScopeInput(_extraScopesToConsent);

            authenticationRequestParameters.LoginHint = loginHint;
            if (!string.IsNullOrWhiteSpace(authenticationRequestParameters.ExtraQueryParameters) &&
                authenticationRequestParameters.ExtraQueryParameters[0] == '&')
            {
                authenticationRequestParameters.ExtraQueryParameters =
                    authenticationRequestParameters.ExtraQueryParameters.Substring(1);
            }

            _webUi        = webUI;
            _UIBehavior   = UIBehavior;
            LoadFromCache = false; //no cache lookup and refresh for interactive.
            AuthenticationRequestParameters.RequestContext.Logger.Info("Additional scopes - " + _extraScopesToConsent.AsSingleString() + ";" + "UIBehavior - " + _UIBehavior.PromptValue);
        }
Example #3
0
        public void LogState()
        {
            StringBuilder builder = new StringBuilder(Environment.NewLine + "=== Request Data ===" +
                                                      Environment.NewLine +
                                                      "Authority Provided? - " + (Authority != null) +
                                                      Environment.NewLine);

            builder.AppendLine("Client Id - " + ClientId);
            builder.AppendLine("Scopes - " + Scope?.AsSingleString());
            builder.AppendLine("Redirect Uri - " + RedirectUri?.OriginalString);
            builder.AppendLine("Validate Authority? - " + ValidateAuthority);
            builder.AppendLine("LoginHint provided? - " + !string.IsNullOrEmpty(LoginHint));
            builder.AppendLine("User provided? - " + (User != null));
            var dict = MsalHelpers.ParseKeyValueList(ExtraQueryParameters, '&', true, RequestContext);

            builder.AppendLine("Extra Query Params Keys (space separated) - " + dict.Keys.AsSingleString());
            dict = MsalHelpers.ParseKeyValueList(ExtraQueryParameters, '&', true, RequestContext);
            builder.AppendLine("Slice Parameters Keys(space separated) - " + dict.Keys.AsSingleString());
#if DESKTOP || NETSTANDARD1_3
            builder.AppendLine("Confidential Client? - " + (ClientCredential != null));
            builder.AppendLine("Client Credential Request? - " + IsClientCredentialRequest);
            if (IsClientCredentialRequest)
            {
                builder.AppendLine("Client Certificate Provided? - " + (ClientCredential.Certificate != null));
            }
#endif
            RequestContext.Logger.Info(builder.ToString());
        }
Example #4
0
        public async Task <AuthorizationResult> AcquireAuthorizationAsync(Uri authorizationUri, Uri redirectUri, RequestContext requestContext)
        {
            if (ExceptionToThrow != null)
            {
                throw ExceptionToThrow;
            }

            IDictionary <string, string> inputQp = MsalHelpers.ParseKeyValueList(authorizationUri.Query.Substring(1), '&', true, null);

            Assert.IsNotNull(inputQp[OAuth2Parameter.State]);
            if (AddStateInAuthorizationResult)
            {
                MockResult.State = inputQp[OAuth2Parameter.State];
            }

            //match QP passed in for validation.
            if (QueryParamsToValidate != null)
            {
                Assert.IsNotNull(authorizationUri.Query);
                foreach (var key in QueryParamsToValidate.Keys)
                {
                    Assert.IsTrue(inputQp.ContainsKey(key));
                    Assert.AreEqual(QueryParamsToValidate[key], inputQp[key]);
                }
            }

            return(await Task.Factory.StartNew(() => MockResult).ConfigureAwait(false));
        }
Example #5
0
        protected override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            if (ExceptionToThrow != null)
            {
                throw ExceptionToThrow;
            }

            Assert.AreEqual(Method, request.Method);

            Uri uri = request.RequestUri;

            if (!string.IsNullOrEmpty(Url))
            {
                Assert.AreEqual(Url, uri.AbsoluteUri.Split(new[] { '?' })[0]);
            }

            //match QP passed in for validation.
            if (QueryParams != null)
            {
                Assert.IsFalse(string.IsNullOrEmpty(uri.Query),
                               string.Format(CultureInfo.InvariantCulture,
                                             "provided url ({0}) does not contain query parameters, as expected", uri.AbsolutePath));
                IDictionary <string, string> inputQp = MsalHelpers.ParseKeyValueList(uri.Query.Substring(1), '&', false, null);
                foreach (var key in QueryParams.Keys)
                {
                    Assert.IsTrue(inputQp.ContainsKey(key),
                                  string.Format(CultureInfo.InvariantCulture,
                                                "expected QP ({0}) not found in the url ({1})", key, uri.AbsolutePath));
                    Assert.AreEqual(QueryParams[key], inputQp[key]);
                }
            }

            //match QP passed in for validation.
            if (QueryParams != null)
            {
                Assert.IsFalse(string.IsNullOrEmpty(uri.Query));
                IDictionary <string, string> inputQp = MsalHelpers.ParseKeyValueList(uri.Query.Substring(1), '&', false, null);
                foreach (var key in QueryParams.Keys)
                {
                    Assert.IsTrue(inputQp.ContainsKey(key));
                    Assert.AreEqual(QueryParams[key], inputQp[key]);
                }
            }

            if (PostData != null)
            {
                string postData = request.Content.ReadAsStringAsync().Result;
                Dictionary <string, string> requestPostDataPairs = MsalHelpers.ParseKeyValueList(postData, '&', true, null);

                foreach (var key in PostData.Keys)
                {
                    Assert.IsTrue(requestPostDataPairs.ContainsKey(key));
                    Assert.AreEqual(PostData[key], requestPostDataPairs[key]);
                }
            }

            return(new TaskFactory().StartNew(() => ResponseMessage, cancellationToken));
        }
Example #6
0
 private void WebBrowserNavigatedHandler(object sender, WebBrowserNavigatedEventArgs e)
 {
     if (!this.CheckForClosingUrl(e.Url))
     {
         PlatformPlugin.Logger.Verbose(null,
                                       string.Format(CultureInfo.InvariantCulture, "Navigated to '{0}'.",
                                                     MsalHelpers.UrlDecode(e.Url.ToString())));
     }
 }
        public string GenerateCodeVerifier()
        {
            byte[] buffer        = new byte[Constants.CodeVerifierByteSize];
            var    windowsBuffer = CryptographicBuffer.GenerateRandom((uint)buffer.Length);

            Array.Copy(windowsBuffer.ToArray(), buffer, buffer.Length);

            return(MsalHelpers.EncodeToBase64Url(buffer));
        }
Example #8
0
        public string GenerateCodeVerifier()
        {
            byte[] buffer = new byte[Internal.Constants.CodeVerifierByteSize];
            using (RNGCryptoServiceProvider randomSource = new RNGCryptoServiceProvider())
            {
                randomSource.GetBytes(buffer);
            }

            return(MsalHelpers.EncodeToBase64Url(buffer));
        }
Example #9
0
        public ICollection <string> GetAllAccessTokensAsString()
        {
            ICollection <string> list = new List <string>();

            foreach (ApplicationDataCompositeValue item in _accessTokenContainer.Values.Values)
            {
                list.Add(MsalHelpers.CreateString(GetCacheValue(item)));
            }

            return(list);
        }
        /// <summary>
        /// Returns the hash code for this TokenCacheKey.
        /// </summary>
        /// <returns>
        /// A 32-bit signed integer hash code.
        /// </returns>
        public override int GetHashCode()
        {
            const string Delimiter = ":::";

            return((this.Authority + Delimiter
                    + MsalHelpers.AsSingleString(this.Scope) + Delimiter
                    + this.ClientId.ToLower() + Delimiter
                    + this.UniqueId + Delimiter
                    + this.HomeObjectId + Delimiter
                    + ((this.DisplayableId != null) ? this.DisplayableId.ToLower() : null) + Delimiter
                    + ((this.Policy != null) ? this.Policy.ToLower() : null)).GetHashCode());
        }
Example #11
0
        private void WebBrowserNavigatedHandler(object sender, WebBrowserNavigatedEventArgs e)
        {
            // Guard condition
            if (CheckForClosingUrl(e.Url))
            {
                return;
            }

            string urlDecode = MsalHelpers.UrlDecode(e.Url.ToString());
            string message   = string.Format(CultureInfo.InvariantCulture, "Navigated to '{0}'.", urlDecode);

            RequestContext.Logger.VerbosePii(message);
        }
        /// <summary>
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            StringBuilder stringBuilder = new StringBuilder();

            stringBuilder.Append(MsalHelpers.Base64Encode(Authority) + "$");
            stringBuilder.Append(MsalHelpers.Base64Encode(ClientId) + "$");
            // scope is treeSet to guarantee the order of the scopes when converting to string.
            stringBuilder.Append(MsalHelpers.Base64Encode(Scope.AsSingleString()) + "$");
            stringBuilder.Append(MsalHelpers.Base64Encode(DisplayableId) + "$");
            stringBuilder.Append(MsalHelpers.Base64Encode(UniqueId) + "$");
            stringBuilder.Append(MsalHelpers.Base64Encode(HomeObjectId) + "$");
            stringBuilder.Append(MsalHelpers.Base64Encode(Policy));

            return(stringBuilder.ToString());
        }
Example #13
0
        public TokenCacheItem(string authority, string clientId, string policy, TokenResponse response)
            : base(authority, clientId, policy, response)
        {
            if (response.AccessToken != null)
            {
                Token = response.AccessToken;
                ExpiresOnUnixTimestamp = MsalHelpers.DateTimeToUnixTimestamp(response.AccessTokenExpiresOn);
            }
            else if (response.IdToken != null)
            {
                Token = response.IdToken;
                ExpiresOnUnixTimestamp = MsalHelpers.DateTimeToUnixTimestamp(response.IdTokenExpiresOn);
            }

            Scope = response.Scope.AsSet();
        }
Example #14
0
        public AccessTokenCacheItem(string authority, string clientId, TokenResponse response)
            : base(clientId)
        {
            TokenType = response.TokenType;
            Scope     = response.Scope;
            Authority = authority;
            if (response.AccessToken != null)
            {
                AccessToken            = response.AccessToken;
                ExpiresOnUnixTimestamp = MsalHelpers.DateTimeToUnixTimestamp(response.AccessTokenExpiresOn);
            }

            RawClientInfo = response.ClientInfo;
            RawIdToken    = response.IdToken;
            CreateDerivedProperties();
        }
        private Uri CreateAuthorizationUri(bool addVerifier = false, bool addState = false)
        {
            IDictionary <string, string> requestParameters = this.CreateAuthorizationRequestParameters();

            if (addVerifier)
            {
                _codeVerifier = PlatformPlugin.CryptographyHelper.GenerateCodeVerifier();
                string codeVerifierHash = PlatformPlugin.CryptographyHelper.CreateSha256Hash(_codeVerifier);

                requestParameters[OAuth2Parameter.CodeChallenge]       = MsalHelpers.EncodeToBase64Url(codeVerifierHash);
                requestParameters[OAuth2Parameter.CodeChallengeMethod] = OAuth2Value.CodeChallengeMethodValue;
            }

            if (addState)
            {
                _state = Guid.NewGuid().ToString();
                requestParameters[OAuth2Parameter.State] = _state;
            }

            if (!string.IsNullOrWhiteSpace(AuthenticationRequestParameters.ExtraQueryParameters))
            {
                // Checks for _extraQueryParameters duplicating standard parameters
                Dictionary <string, string> kvps =
                    MsalHelpers.ParseKeyValueList(AuthenticationRequestParameters.ExtraQueryParameters, '&', false,
                                                  this.CallState);

                foreach (KeyValuePair <string, string> kvp in kvps)
                {
                    if (requestParameters.ContainsKey(kvp.Key))
                    {
                        throw new MsalException(MsalError.DuplicateQueryParameter,
                                                string.Format(CultureInfo.InvariantCulture, MsalErrorMessage.DuplicateQueryParameterTemplate,
                                                              kvp.Key));
                    }
                }
            }

            string qp = requestParameters.ToQueryParameter();

            if (!string.IsNullOrEmpty(AuthenticationRequestParameters.ExtraQueryParameters))
            {
                qp += "&" + AuthenticationRequestParameters.ExtraQueryParameters;
            }

            return(new Uri(new Uri(this.Authority.AuthorizationEndpoint), "?" + qp));
        }
Example #16
0
        public void GetAuthorizationRequestUrlCustomRedirectUriTest()
        {
            ConfidentialClientApplication app =
                new ConfidentialClientApplication(TestConstants.ClientId, TestConstants.AuthorityGuestTenant,
                                                  TestConstants.RedirectUri, new ClientCredential(TestConstants.ClientSecret),
                                                  new TokenCache(), new TokenCache())
            {
                ValidateAuthority = false
            };

            //add mock response for tenant endpoint discovery
            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler
            {
                Method          = HttpMethod.Get,
                ResponseMessage = MockHelpers.CreateOpenIdConfigurationResponse(app.Authority)
            });

            const string CustomRedirectUri = "custom://redirect-uri";
            Task <Uri>   task = app.GetAuthorizationRequestUrlAsync(TestConstants.Scope.AsArray(),
                                                                    CustomRedirectUri, TestConstants.DisplayableId, "extra=qp",
                                                                    TestConstants.ScopeForAnotherResource.AsArray(), TestConstants.AuthorityGuestTenant);
            Uri uri = task.Result;

            Assert.IsNotNull(uri);
            Assert.IsTrue(uri.AbsoluteUri.StartsWith(TestConstants.AuthorityGuestTenant, StringComparison.CurrentCulture));
            Dictionary <string, string> qp = MsalHelpers.ParseKeyValueList(uri.Query.Substring(1), '&', true, null);

            Assert.IsNotNull(qp);
            Assert.AreEqual(12, qp.Count);
            Assert.IsTrue(qp.ContainsKey("client-request-id"));
            Assert.IsFalse(qp.ContainsKey("client_secret"));
            Assert.AreEqual("offline_access openid profile r1/scope1 r1/scope2 r2/scope1 r2/scope2", qp["scope"]);
            Assert.AreEqual(TestConstants.ClientId, qp["client_id"]);
            Assert.AreEqual("code", qp["response_type"]);
            Assert.AreEqual(CustomRedirectUri, qp["redirect_uri"]);
            Assert.AreEqual(TestConstants.DisplayableId, qp["login_hint"]);
            Assert.AreEqual("MSAL.Desktop", qp["x-client-sku"]);
            Assert.IsFalse(string.IsNullOrEmpty(qp["x-client-ver"]));
            Assert.IsFalse(string.IsNullOrEmpty(qp["x-client-cpu"]));
            Assert.IsFalse(string.IsNullOrEmpty(qp["x-client-os"]));
            Assert.AreEqual("qp", qp["extra"]);
            Assert.AreEqual("select_account", qp["prompt"]);

            Assert.IsTrue(HttpMessageHandlerFactory.IsMocksQueueEmpty, "All mocks should have been consumed");
        }
Example #17
0
        public void GetIntersectedScopesMatchedAccessTokenTest()
        {
            TokenCache cache = new TokenCache()
            {
                ClientId = TestConstants.ClientId
            };
            AccessTokenCacheItem atItem = new AccessTokenCacheItem()
            {
                Authority = TestConstants.AuthorityHomeTenant,
                ClientId  = TestConstants.ClientId,
                TokenType = "Bearer",
                ScopeSet  = TestConstants.Scope,
                ExpiresOnUnixTimestamp = MsalHelpers.DateTimeToUnixTimestamp(DateTime.UtcNow + TimeSpan.FromHours(1)),
                RawIdToken             = MockHelpers.CreateIdToken(TestConstants.UniqueId, TestConstants.DisplayableId)
            };

            // create key out of access token cache item and then
            // set it as the value of the access token.
            AccessTokenCacheKey atKey = atItem.GetAccessTokenItemKey();

            atItem.AccessToken = atKey.ToString();
            cache.TokenCacheAccessor.AccessTokenCacheDictionary[atKey.ToString()] = JsonHelper.SerializeToJson(atItem);

            var param = new AuthenticationRequestParameters()
            {
                RequestContext = new RequestContext(Guid.Empty, null),
                ClientId       = TestConstants.ClientId,
                Authority      = Authority.CreateAuthority(TestConstants.AuthorityHomeTenant, false),
                Scope          = new SortedSet <string>(),
                User           =
                    new User()
                {
                    DisplayableId = TestConstants.DisplayableId,
                    Identifier    = TestConstants.UserIdentifier
                }
            };

            param.Scope.Add(TestConstants.Scope.First());
            param.Scope.Add("non-existant-scopes");
            AccessTokenCacheItem item = cache.FindAccessToken(param);

            //intersected scopes are not returned.
            Assert.IsNull(item);
        }
Example #18
0
        public void GetSubsetScopesMatchedAccessTokenTest()
        {
            TokenCache cache = new TokenCache()
            {
                ClientId = TestConstants.ClientId
            };
            AccessTokenCacheItem atItem = new AccessTokenCacheItem()
            {
                Authority = TestConstants.AuthorityHomeTenant,
                ClientId  = TestConstants.ClientId,
                TokenType = "Bearer",
                ScopeSet  = TestConstants.Scope,
                Scope     = TestConstants.Scope.AsSingleString(),
                ExpiresOnUnixTimestamp = MsalHelpers.DateTimeToUnixTimestamp(DateTime.UtcNow + TimeSpan.FromHours(1)),
                RawIdToken             = MockHelpers.CreateIdToken(TestConstants.UniqueId, TestConstants.DisplayableId),
                RawClientInfo          = MockHelpers.CreateClientInfo(),
            };

            atItem.IdToken    = IdToken.Parse(atItem.RawIdToken);
            atItem.ClientInfo = ClientInfo.CreateFromJson(atItem.RawClientInfo);

            // create key out of access token cache item and then
            // set it as the value of the access token.
            AccessTokenCacheKey atKey = atItem.GetAccessTokenItemKey();

            atItem.AccessToken = atKey.ToString();

            cache.TokenCacheAccessor.AccessTokenCacheDictionary[atKey.ToString()] = JsonHelper.SerializeToJson(atItem);
            var param = new AuthenticationRequestParameters()
            {
                RequestContext = new RequestContext(Guid.Empty, null),
                ClientId       = TestConstants.ClientId,
                Authority      = Authority.CreateAuthority(TestConstants.AuthorityHomeTenant, false),
                Scope          = new SortedSet <string>(),
                User           = TestConstants.User
            };

            param.Scope.Add("r1/scope1");
            AccessTokenCacheItem item = cache.FindAccessToken(param);

            Assert.IsNotNull(item);
            Assert.AreEqual(atKey.ToString(), item.AccessToken);
        }
Example #19
0
        /// <summary>
        /// </summary>
        protected virtual void WebBrowserNavigatingHandler(object sender, WebBrowserNavigatingEventArgs e)
        {
            if (this.DialogResult == DialogResult.OK)
            {
                e.Cancel = true;
                return;
            }

            if (this.webBrowser.IsDisposed)
            {
                // we cancel all flows in disposed object and just do nothing, let object to close.
                // it just for safety.
                e.Cancel = true;
                return;
            }

            if (key == Keys.Back)
            {
                //navigation is being done via back key. This needs to be disabled.
                key      = Keys.None;
                e.Cancel = true;
            }

            // we cancel further processing, if we reached final URL.
            // Security issue: we prohibit navigation with auth code
            // if redirect URI is URN, then we prohibit navigation, to prevent random browser popup.
            e.Cancel = this.CheckForClosingUrl(e.Url);

            // check if the url scheme is of type browser-install://
            // this means we need to launch external browser
            if (e.Url.Scheme.Equals("browser", StringComparison.OrdinalIgnoreCase))
            {
                Process.Start(e.Url.AbsoluteUri.Replace("browser://", "https://"));
                e.Cancel = true;
            }

            if (!e.Cancel)
            {
                PlatformPlugin.Logger.Verbose(null,
                                              string.Format(CultureInfo.InvariantCulture, "Navigating to '{0}'.",
                                                            MsalHelpers.UrlDecode(e.Url.ToString())));
            }
        }
Example #20
0
        public void GetExpiredAccessTokenTest()
        {
            cache = new TokenCache()
            {
                ClientId = TestConstants.ClientId
            };

            AccessTokenCacheItem item = new AccessTokenCacheItem()
            {
                Authority = TestConstants.AuthorityHomeTenant,
                ClientId  = TestConstants.ClientId,
                TokenType = "Bearer",
                ExpiresOnUnixTimestamp = MsalHelpers.DateTimeToUnixTimestamp(DateTime.UtcNow),
                RawIdToken             = MockHelpers.CreateIdToken(TestConstants.UniqueId, TestConstants.DisplayableId),
                RawClientInfo          = MockHelpers.CreateClientInfo(),
                ScopeSet = TestConstants.Scope
            };

            item.IdToken     = IdToken.Parse(item.RawIdToken);
            item.ClientInfo  = ClientInfo.CreateFromJson(item.RawClientInfo);
            item.AccessToken = item.GetAccessTokenItemKey().ToString();
            cache.TokenCacheAccessor.AccessTokenCacheDictionary[item.GetAccessTokenItemKey().ToString()] =
                JsonHelper.SerializeToJson(item);

            cache.TokenCacheAccessor.AccessTokenCacheDictionary[item.GetAccessTokenItemKey().ToString()] =
                JsonHelper.SerializeToJson(item);

            Assert.IsNull(cache.FindAccessToken(new AuthenticationRequestParameters()
            {
                RequestContext = new RequestContext(Guid.Empty, null),
                ClientId       = TestConstants.ClientId,
                Authority      = Authority.CreateAuthority(TestConstants.AuthorityHomeTenant, false),
                Scope          = TestConstants.Scope,
                User           =
                    new User()
                {
                    DisplayableId = TestConstants.DisplayableId,
                    Identifier    = TestConstants.UserIdentifier
                }
            }));
        }
Example #21
0
        public void GetAccessTokenMatchedUserAssertionInCacheTest()
        {
            TokenCache cache = new TokenCache()
            {
                ClientId = TestConstants.ClientId
            };
            AccessTokenCacheItem atItem = new AccessTokenCacheItem()
            {
                Authority = TestConstants.AuthorityHomeTenant,
                ClientId  = TestConstants.ClientId,
                TokenType = "Bearer",
                ScopeSet  = TestConstants.Scope,
                Scope     = TestConstants.Scope.AsSingleString(),
                ExpiresOnUnixTimestamp = MsalHelpers.DateTimeToUnixTimestamp(DateTime.UtcNow + TimeSpan.FromHours(1)),
                RawIdToken             = MockHelpers.CreateIdToken(TestConstants.UniqueId, TestConstants.DisplayableId)
            };

            // create key out of access token cache item and then
            // set it as the value of the access token.
            AccessTokenCacheKey atKey = atItem.GetAccessTokenItemKey();

            atItem.AccessToken       = atKey.ToString();
            atItem.UserAssertionHash = CryptographyHelper.CreateBase64UrlEncodedSha256Hash(atKey.ToString());

            cache.TokenCacheAccessor.AccessTokenCacheDictionary[atKey.ToString()] = JsonHelper.SerializeToJson(atItem);
            var param = new AuthenticationRequestParameters()
            {
                RequestContext = new RequestContext(Guid.Empty, null),
                ClientId       = TestConstants.ClientId,
                Authority      = Authority.CreateAuthority(TestConstants.AuthorityHomeTenant, false),
                Scope          = TestConstants.Scope,
                UserAssertion  = new UserAssertion(atKey.ToString())
            };

            cache.AfterAccess = AfterAccessNoChangeNotification;
            AccessTokenCacheItem item = cache.FindAccessToken(param);

            Assert.IsNotNull(item);
            Assert.AreEqual(atKey.ToString(), item.AccessToken);
        }
Example #22
0
        public void GetAuthorizationRequestUrlB2CTest()
        {
            ConfidentialClientApplication app = new ConfidentialClientApplication(TestConstants.ClientId,
                                                                                  TestConstants.RedirectUri, new ClientCredential(TestConstants.ClientSecret),
                                                                                  new TokenCache(), new TokenCache())
            {
                ValidateAuthority = false
            };

            //add mock response for tenant endpoint discovery
            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler
            {
                Method          = HttpMethod.Get,
                ResponseMessage = MockHelpers.CreateSuccessResponseMessage(File.ReadAllText(@"OpenidConfiguration-B2C.json"))
            });

            Task <Uri> task = app.GetAuthorizationRequestUrlAsync(TestConstants.Scope.AsArray(),
                                                                  TestConstants.DisplayableId, null);
            Uri uri = task.Result;

            Assert.IsNotNull(uri);
            Dictionary <string, string> qp = MsalHelpers.ParseKeyValueList(uri.Query.Substring(1), '&', true, null);

            Assert.IsNotNull(qp);
            Assert.AreEqual(12, qp.Count);
            Assert.AreEqual("my-policy", qp["p"]);
            Assert.IsTrue(qp.ContainsKey("client-request-id"));
            Assert.AreEqual("offline_access openid profile r1/scope1 r1/scope2", qp["scope"]);
            Assert.AreEqual(TestConstants.ClientId, qp["client_id"]);
            Assert.AreEqual("code", qp["response_type"]);
            Assert.AreEqual(TestConstants.RedirectUri, qp["redirect_uri"]);
            Assert.AreEqual(TestConstants.DisplayableId, qp["login_hint"]);
            Assert.AreEqual(UIBehavior.SelectAccount.PromptValue, qp["prompt"]);
            Assert.AreEqual("MSAL.Desktop", qp["x-client-sku"]);
            Assert.IsFalse(string.IsNullOrEmpty(qp["x-client-ver"]));
            Assert.IsFalse(string.IsNullOrEmpty(qp["x-client-cpu"]));
            Assert.IsFalse(string.IsNullOrEmpty(qp["x-client-os"]));

            Assert.IsTrue(HttpMessageHandlerFactory.IsMocksQueueEmpty, "All mocks should have been consumed");
        }
Example #23
0
        public static void PopulateCache(TokenCacheAccessor accessor)
        {
            AccessTokenCacheItem item = new AccessTokenCacheItem()
            {
                Authority = TestConstants.AuthorityHomeTenant,
                ClientId  = TestConstants.ClientId,
                TokenType = "Bearer",
                ExpiresOnUnixTimestamp = MsalHelpers.DateTimeToUnixTimestamp(new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(ValidExpiresIn))),
                RawIdToken             = MockHelpers.CreateIdToken(TestConstants.UniqueId, TestConstants.DisplayableId),
                RawClientInfo          = MockHelpers.CreateClientInfo(),
                Scope    = TestConstants.Scope.AsSingleString(),
                ScopeSet = TestConstants.Scope
            };

            item.IdToken     = IdToken.Parse(item.RawIdToken);
            item.ClientInfo  = ClientInfo.CreateFromJson(item.RawClientInfo);
            item.AccessToken = item.GetAccessTokenItemKey().ToString();
            //add access token
            accessor.AccessTokenCacheDictionary[item.GetAccessTokenItemKey().ToString()] = JsonHelper.SerializeToJson(item);

            item = new AccessTokenCacheItem()
            {
                Authority = TestConstants.AuthorityGuestTenant,
                ClientId  = TestConstants.ClientId,
                TokenType = "Bearer",
                ExpiresOnUnixTimestamp = MsalHelpers.DateTimeToUnixTimestamp(new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(ValidExpiresIn))),
                RawIdToken             = MockHelpers.CreateIdToken(TestConstants.UniqueId + "more", TestConstants.DisplayableId),
                RawClientInfo          = MockHelpers.CreateClientInfo(),
                Scope    = TestConstants.ScopeForAnotherResource.AsSingleString(),
                ScopeSet = TestConstants.ScopeForAnotherResource
            };
            item.IdToken     = IdToken.Parse(item.RawIdToken);
            item.ClientInfo  = ClientInfo.CreateFromJson(item.RawClientInfo);
            item.AccessToken = item.GetAccessTokenItemKey().ToString();
            //add another access token
            accessor.AccessTokenCacheDictionary[item.GetAccessTokenItemKey().ToString()] = JsonHelper.SerializeToJson(item);

            AddRefreshTokenToCache(accessor, TestConstants.Uid, TestConstants.Utid, TestConstants.Name);
        }
Example #24
0
        public void GetAccessTokenUserAssertionMismatchInCacheTest()
        {
            TokenCache cache = new TokenCache()
            {
                ClientId = TestConstants.ClientId
            };
            AccessTokenCacheItem atItem = new AccessTokenCacheItem()
            {
                Authority = TestConstants.AuthorityHomeTenant,
                ClientId  = TestConstants.ClientId,
                TokenType = "Bearer",
                ScopeSet  = TestConstants.Scope,
                ExpiresOnUnixTimestamp = MsalHelpers.DateTimeToUnixTimestamp(DateTime.UtcNow + TimeSpan.FromHours(1)),
                RawIdToken             = MockHelpers.CreateIdToken(TestConstants.UniqueId, TestConstants.DisplayableId)
            };

            // create key out of access token cache item and then
            // set it as the value of the access token.
            AccessTokenCacheKey atKey = atItem.GetAccessTokenItemKey();

            atItem.AccessToken       = atKey.ToString();
            atItem.UserAssertionHash = CryptographyHelper.CreateBase64UrlEncodedSha256Hash(atKey.ToString());

            cache.TokenCacheAccessor.AccessTokenCacheDictionary[atKey.ToString()] = JsonHelper.SerializeToJson(atItem);
            var param = new AuthenticationRequestParameters()
            {
                RequestContext = new RequestContext(Guid.Empty, null),
                ClientId       = TestConstants.ClientId,
                Authority      = Authority.CreateAuthority(TestConstants.AuthorityHomeTenant, false),
                Scope          = TestConstants.Scope,
                UserAssertion  = new UserAssertion(atItem.UserAssertionHash + "-random")
            };

            AccessTokenCacheItem item = cache.FindAccessToken(param);

            // cache lookup should fail because there was userassertion hash did not match the one
            // stored in token cache item.
            Assert.IsNull(item);
        }
        private void CheckForDuplicateQueryParameters(string queryParams, IDictionary <string, string> requestParameters)
        {
            if (!string.IsNullOrWhiteSpace(queryParams))
            {
                // Checks for _extraQueryParameters duplicating standard parameters
                Dictionary <string, string> kvps =
                    MsalHelpers.ParseKeyValueList(queryParams, '&', false,
                                                  AuthenticationRequestParameters.RequestContext);

                foreach (KeyValuePair <string, string> kvp in kvps)
                {
                    if (requestParameters.ContainsKey(kvp.Key))
                    {
                        throw new MsalClientException(MsalClientException.DuplicateQueryParameterError,
                                                      string.Format(CultureInfo.InvariantCulture, MsalErrorMessage.DuplicateQueryParameterTemplate,
                                                                    kvp.Key));
                    }

                    requestParameters[kvp.Key] = kvp.Value;
                }
            }
        }
        public InteractiveRequest(AuthenticationRequestParameters authenticationRequestParameters,
                                  string[] additionalScope, string loginHint,
                                  UiOptions?uiOptions, IWebUI webUI)
            : base(authenticationRequestParameters)
        {
            PlatformPlugin.PlatformInformation.ValidateRedirectUri(authenticationRequestParameters.RedirectUri,
                                                                   this.CallState);
            if (!string.IsNullOrWhiteSpace(authenticationRequestParameters.RedirectUri.Fragment))
            {
                throw new ArgumentException(MsalErrorMessage.RedirectUriContainsFragment, "redirectUri");
            }

            _additionalScope = new SortedSet <string>();
            if (!MsalHelpers.IsNullOrEmpty(additionalScope))
            {
                this._additionalScope = additionalScope.CreateSetFromArray();
            }

            ValidateScopeInput(this._additionalScope);

            authenticationRequestParameters.LoginHint = loginHint;
            if (!string.IsNullOrWhiteSpace(authenticationRequestParameters.ExtraQueryParameters) &&
                authenticationRequestParameters.ExtraQueryParameters[0] == '&')
            {
                authenticationRequestParameters.ExtraQueryParameters =
                    authenticationRequestParameters.ExtraQueryParameters.Substring(1);
            }

            this._webUi        = webUI;
            this._uiOptions    = uiOptions;
            this.LoadFromCache = false; //no cache lookup and refresh for interactive.

            if (string.IsNullOrWhiteSpace(loginHint) && _uiOptions == UiOptions.ActAsCurrentUser)
            {
                throw new ArgumentException(MsalErrorMessage.LoginHintNullForUiOption, "loginHint");
            }

            PlatformPlugin.BrokerHelper.PlatformParameters = authenticationRequestParameters.PlatformParameters;
        }
Example #27
0
        public void GetAppTokenFromCacheTest()
        {
            cache = new TokenCache()
            {
                ClientId = TestConstants.ClientId
            };

            AccessTokenCacheItem item = new AccessTokenCacheItem()
            {
                Authority = TestConstants.AuthorityHomeTenant,
                ClientId  = TestConstants.ClientId,
                TokenType = "Bearer",
                ExpiresOnUnixTimestamp =
                    MsalHelpers.DateTimeToUnixTimestamp(DateTime.UtcNow + TimeSpan.FromSeconds(ValidExpiresIn)),
                RawIdToken    = null,
                RawClientInfo = null,
                User          = null,
                Scope         = TestConstants.Scope.AsSingleString(),
                ScopeSet      = TestConstants.Scope
            };

            item.AccessToken = item.GetAccessTokenItemKey().ToString();
            cache.TokenCacheAccessor.AccessTokenCacheDictionary[item.GetAccessTokenItemKey().ToString()] =
                JsonHelper.SerializeToJson(item);

            AccessTokenCacheItem cacheItem = cache.FindAccessToken(new AuthenticationRequestParameters()
            {
                IsClientCredentialRequest = true,
                RequestContext            = new RequestContext(Guid.Empty, null),
                Authority        = Authority.CreateAuthority(TestConstants.AuthorityHomeTenant, false),
                ClientId         = TestConstants.ClientId,
                ClientCredential = TestConstants.CredentialWithSecret,
                Scope            = TestConstants.Scope
            });

            Assert.IsNotNull(cacheItem);
            Assert.AreEqual(item.GetAccessTokenItemKey().ToString(), cacheItem.GetAccessTokenItemKey().ToString());
        }
Example #28
0
 public string GetRefreshToken(string refreshTokenKey)
 {
     return(MsalHelpers.ByteArrayToString(
                GetCacheValue((ApplicationDataCompositeValue)_refreshTokenContainer.Values[
                                  CryptographyHelper.CreateBase64UrlEncodedSha256Hash(refreshTokenKey)])));
 }
Example #29
0
 protected static long CurrentUnixTimeMilliseconds()
 {
     return(MsalHelpers.DateTimeToUnixTimestampMilliseconds(DateTimeOffset.Now));
 }
Example #30
0
        public void GetUsersTest()
        {
            PublicClientApplication app   = new PublicClientApplication(TestConstants.ClientId);
            IEnumerable <IUser>     users = app.Users;

            Assert.IsNotNull(users);
            Assert.IsFalse(users.Any());
            cache = new TokenCache()
            {
                ClientId = TestConstants.ClientId
            };

            app.UserTokenCache = cache;
            TokenCacheHelper.PopulateCache(cache.TokenCacheAccessor);
            users = app.Users;
            Assert.IsNotNull(users);
            Assert.AreEqual(1, users.Count());

            AccessTokenCacheItem item = new AccessTokenCacheItem()
            {
                Authority = TestConstants.AuthorityHomeTenant,
                ClientId  = TestConstants.ClientId,
                TokenType = "Bearer",
                ExpiresOnUnixTimestamp =
                    MsalHelpers.DateTimeToUnixTimestamp((DateTime.UtcNow + TimeSpan.FromSeconds(3600))),
                RawIdToken    = MockHelpers.CreateIdToken(TestConstants.UniqueId, TestConstants.DisplayableId),
                RawClientInfo = MockHelpers.CreateClientInfo(),
                ScopeSet      = TestConstants.Scope
            };

            item.IdToken     = IdToken.Parse(item.RawIdToken);
            item.ClientInfo  = ClientInfo.CreateFromJson(item.RawClientInfo);
            item.AccessToken = item.GetAccessTokenItemKey().ToString();
            cache.TokenCacheAccessor.AccessTokenCacheDictionary[item.GetAccessTokenItemKey().ToString()] =
                JsonHelper.SerializeToJson(item);


            // another cache entry for different uid. user count should be 2.
            RefreshTokenCacheItem rtItem = new RefreshTokenCacheItem()
            {
                Environment      = TestConstants.ProductionEnvironment,
                ClientId         = TestConstants.ClientId,
                RefreshToken     = "someRT",
                RawClientInfo    = MockHelpers.CreateClientInfo(TestConstants.Uid + "more", TestConstants.Utid),
                DisplayableId    = TestConstants.DisplayableId,
                IdentityProvider = TestConstants.IdentityProvider,
                Name             = TestConstants.Name
            };

            rtItem.ClientInfo = ClientInfo.CreateFromJson(rtItem.RawClientInfo);
            cache.TokenCacheAccessor.RefreshTokenCacheDictionary[rtItem.GetRefreshTokenItemKey().ToString()] =
                JsonHelper.SerializeToJson(rtItem);
            Assert.AreEqual(2, cache.TokenCacheAccessor.RefreshTokenCacheDictionary.Count);
            users = app.Users;
            Assert.IsNotNull(users);
            Assert.AreEqual(2, users.Count());

            // another cache entry for different environment. user count should still be 2. Sovereign cloud user must not be returned
            rtItem = new RefreshTokenCacheItem()
            {
                Environment      = TestConstants.SovereignEnvironment,
                ClientId         = TestConstants.ClientId,
                RefreshToken     = "someRT",
                RawClientInfo    = MockHelpers.CreateClientInfo(TestConstants.Uid + "more1", TestConstants.Utid),
                DisplayableId    = TestConstants.DisplayableId,
                IdentityProvider = TestConstants.IdentityProvider,
                Name             = TestConstants.Name
            };
            rtItem.ClientInfo = ClientInfo.CreateFromJson(rtItem.RawClientInfo);
            cache.TokenCacheAccessor.RefreshTokenCacheDictionary[rtItem.GetRefreshTokenItemKey().ToString()] =
                JsonHelper.SerializeToJson(rtItem);
            Assert.AreEqual(3, cache.TokenCacheAccessor.RefreshTokenCacheDictionary.Count);
            users = app.Users;
            Assert.IsNotNull(users);
            Assert.AreEqual(2, users.Count());
        }