示例#1
0
        public void SilentRefreshFailedNoCacheItemFoundTest()
        {
            using (var harness = new MockHttpTestHarness(TestConstants.AuthorityHomeTenant))
            {
                var parameters = harness.CreateRequestParams(
                    harness.Cache,
                    ScopeHelper.CreateSortedSetFromEnumerable(
                        new[]
                {
                    "some-scope1",
                    "some-scope2"
                }),
                    authorityOverride: AuthorityInfo.FromAuthorityUri(TestConstants.AuthorityHomeTenant, false));

                var silentParameters = new AcquireTokenSilentParameters()
                {
                    Account = new Account(TestConstants.HomeAccountId, TestConstants.DisplayableId, TestConstants.ProductionPrefCacheEnvironment),
                };

                try
                {
                    var request = new SilentRequest(harness.ServiceBundle, parameters, silentParameters);
                    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(MsalError.NoTokensFoundError, exc.ErrorCode);
                }
            }
        }
        protected SortedSet <string> GetDecoratedScope(SortedSet <string> inputScope)
        {
            SortedSet <string> set = new SortedSet <string>(inputScope.ToArray());

            set.UnionWith(ScopeHelper.CreateSortedSetFromEnumerable(OAuth2Value.ReservedScopes));
            return(set);
        }
示例#3
0
        public AuthenticationRequestParameters(
            IServiceBundle serviceBundle,
            ITokenCacheInternal tokenCache,
            AcquireTokenCommonParameters commonParameters,
            RequestContext requestContext)
        {
            _commonParameters = commonParameters;

            Authority = Authority.CreateAuthorityForRequest(serviceBundle.Config.AuthorityInfo, commonParameters.AuthorityOverride);

            ClientId            = serviceBundle.Config.ClientId;
            CacheSessionManager = new CacheSessionManager(tokenCache, this, serviceBundle.TelemetryManager);
            Scope           = ScopeHelper.CreateSortedSetFromEnumerable(commonParameters.Scopes);
            RedirectUri     = new Uri(serviceBundle.Config.RedirectUri);
            RequestContext  = requestContext;
            IsBrokerEnabled = serviceBundle.Config.IsBrokerEnabled;

            // Set application wide query parameters.
            ExtraQueryParameters = serviceBundle.Config.ExtraQueryParameters ?? new Dictionary <string, string>();

            // Copy in call-specific query parameters.
            if (commonParameters.ExtraQueryParameters != null)
            {
                foreach (KeyValuePair <string, string> kvp in commonParameters.ExtraQueryParameters)
                {
                    ExtraQueryParameters[kvp.Key] = kvp.Value;
                }
            }
        }
示例#4
0
        public InteractiveRequest(
            IServiceBundle serviceBundle,
            AuthenticationRequestParameters authenticationRequestParameters,
            ApiEvent.ApiIds apiId,
            IEnumerable <string> extraScopesToConsent,
            string loginHint,
            UIBehavior uiBehavior,
            IWebUI webUi)
            : base(serviceBundle, authenticationRequestParameters, apiId)
        {
            RedirectUriHelper.Validate(authenticationRequestParameters.RedirectUri);
            webUi?.ValidateRedirectUri(authenticationRequestParameters.RedirectUri);

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

            ValidateScopeInput(_extraScopesToConsent);

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

            _webUi      = webUi;
            _uiBehavior = uiBehavior;
            AuthenticationRequestParameters.RequestContext.Logger.Info(
                "Additional scopes - " + _extraScopesToConsent.AsSingleString() + ";" +
                "UIBehavior - " + _uiBehavior.PromptValue);
        }
示例#5
0
        private Dictionary <string, string> CreateAuthorizationRequestParameters(Uri redirectUriOverride = null)
        {
            var extraScopesToConsent = new SortedSet <string>();

            if (!_interactiveParameters.ExtraScopesToConsent.IsNullOrEmpty())
            {
                extraScopesToConsent = ScopeHelper.CreateSortedSetFromEnumerable(_interactiveParameters.ExtraScopesToConsent);
            }

            if (extraScopesToConsent.Contains(_requestParams.ClientId))
            {
                throw new ArgumentException("API does not accept client id as a user-provided scope");
            }

            SortedSet <string> unionScope = GetDecoratedScope(
                new SortedSet <string>(_requestParams.Scope.Union(extraScopesToConsent)));

            var authorizationRequestParameters = new Dictionary <string, string>
            {
                [OAuth2Parameter.Scope]        = unionScope.AsSingleString(),
                [OAuth2Parameter.ResponseType] = OAuth2ResponseType.Code,

                [OAuth2Parameter.ClientId]    = _requestParams.ClientId,
                [OAuth2Parameter.RedirectUri] = redirectUriOverride?.OriginalString ?? _requestParams.RedirectUri.OriginalString
            };

            if (!string.IsNullOrWhiteSpace(_requestParams.ClaimsAndClientCapabilities))
            {
                authorizationRequestParameters[OAuth2Parameter.Claims] = _requestParams.ClaimsAndClientCapabilities;
            }

            if (!string.IsNullOrWhiteSpace(_interactiveParameters.LoginHint))
            {
                authorizationRequestParameters[OAuth2Parameter.LoginHint] = _interactiveParameters.LoginHint;
            }

            if (_requestParams.RequestContext.CorrelationId != Guid.Empty)
            {
                authorizationRequestParameters[OAuth2Parameter.CorrelationId] =
                    _requestParams.RequestContext.CorrelationId.ToString();
            }

            foreach (KeyValuePair <string, string> kvp in MsalIdHelper.GetMsalIdParameters(_requestParams.RequestContext.Logger))
            {
                authorizationRequestParameters[kvp.Key] = kvp.Value;
            }

            if (_interactiveParameters.Prompt.PromptValue != Prompt.NoPrompt.PromptValue)
            {
                authorizationRequestParameters[OAuth2Parameter.Prompt] = _interactiveParameters.Prompt.PromptValue;
            }

            return(authorizationRequestParameters);
        }
        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);
                }
            }
        }
        protected void ValidateScopeInput(SortedSet <string> scopesToValidate)
        {
            // Check if scope or additional scope contains client ID.
            // TODO: instead of failing in the validation, could we simply just remove what the user sets and log that we did so instead?
            if (scopesToValidate.Intersect(ScopeHelper.CreateSortedSetFromEnumerable(OAuth2Value.ReservedScopes)).Any())
            {
                throw new ArgumentException("MSAL always sends the scopes 'openid profile offline_access'. " +
                                            "They cannot be suppressed as they are required for the " +
                                            "library to function. Do not include any of these scopes in the scope parameter.");
            }

            if (scopesToValidate.Contains(AuthenticationRequestParameters.ClientId))
            {
                throw new ArgumentException("API does not accept client id as a user-provided scope");
            }
        }
        public InteractiveRequest(
            IServiceBundle serviceBundle,
            AuthenticationRequestParameters authenticationRequestParameters,
            AcquireTokenInteractiveParameters interactiveParameters,
            IWebUI webUi)
            : base(serviceBundle, authenticationRequestParameters, interactiveParameters)
        {
            _webUi = webUi; // can be null just to generate the authorization uri

            _interactiveParameters = interactiveParameters;
            RedirectUriHelper.Validate(authenticationRequestParameters.RedirectUri);

            // todo(migration): can't this just come directly from interactive parameters instead of needing do to this?
            _extraScopesToConsent = new SortedSet <string>();
            if (!_interactiveParameters.ExtraScopesToConsent.IsNullOrEmpty())
            {
                _extraScopesToConsent = ScopeHelper.CreateSortedSetFromEnumerable(_interactiveParameters.ExtraScopesToConsent);
            }

            ValidateScopeInput(_extraScopesToConsent);

            _interactiveParameters.LogParameters(authenticationRequestParameters.RequestContext.Logger);
        }