private void CreateException(Exception ex)
        {
            string        output    = string.Empty;
            MsalException exception = ex as MsalException;

            if (exception != null)
            {
                output += string.Format(
                    CultureInfo.InvariantCulture,
                    "Error Code - {0}" + Environment.NewLine + "Message - {1}" + Environment.NewLine,
                    exception.ErrorCode,
                    exception.Message);

                if (exception is MsalServiceException)
                {
                    output += string.Format(CultureInfo.InvariantCulture, "Status Code - {0}" + Environment.NewLine, ((MsalServiceException)exception).StatusCode);
                    output += string.Format(CultureInfo.InvariantCulture, "Claims - {0}" + Environment.NewLine, ((MsalServiceException)exception).Claims);
                    output += string.Format(CultureInfo.InvariantCulture, "Raw Response - {0}" + Environment.NewLine, ((MsalServiceException)exception).ResponseBody);
                }
            }
            else
            {
                output = ex.Message + Environment.NewLine + ex.StackTrace;
            }


            callResult.Text = output;
        }
        public void ScrubPiiExceptionsTest()
        {
            Exception ex     = new Exception("test message");
            var       result = ex.GetPiiScrubbedDetails();

            Assert.AreEqual("Exception type: System.Exception", result);

            result = ((Exception)null).GetPiiScrubbedDetails();
            Assert.AreEqual(null, result);

            Exception innerException = new Exception("test message", new Exception("inner message"));

            result = innerException.GetPiiScrubbedDetails();
            Assert.AreEqual("Exception type: System.Exception---> Exception type: System.Exception\r\n=== End of inner exception stack trace ===",
                            result);

            MsalException msalException = new MsalException("Msal Exception");

            result = msalException.GetPiiScrubbedDetails();
            Assert.AreEqual("Exception type: Microsoft.Identity.Client.MsalException, ErrorCode: Msal Exception", result);

            MsalServiceException msalServiceException = new MsalServiceException("ErrorCode", "Msal Service Exception");

            result = msalServiceException.GetPiiScrubbedDetails();
            Assert.AreEqual("Exception type: Microsoft.Identity.Client.MsalServiceException, ErrorCode: ErrorCode, StatusCode: 0", result);
        }
Ejemplo n.º 3
0
        public static IDictionary <string, string> GetExceptionInfo(this MsalException msal, IDictionary <string, string> additionalValues = null)
        {
            var props = new Dictionary <string, string>
            {
                { "Data", JsonConvert.SerializeObject(msal.Data) },
                { "ErrorCode", msal.ErrorCode },
                { "HelpLink", msal.HelpLink },
                { "HResult", $"{msal.HResult}" },
                { "Source", msal.Source },
                { "TargetSite", msal.TargetSite.Name }
            };

            if (msal is MsalServiceException serviceException)
            {
                props.Add("Claims", serviceException.Claims);
                props.Add("ResponseBody", serviceException.ResponseBody);
                props.Add("StatusCode", $"{serviceException.StatusCode}");
            }

            if (additionalValues != null)
            {
                foreach (var pair in additionalValues)
                {
                    props.Add(pair.Key, pair.Value);
                }
            }

            return(props);
        }
Ejemplo n.º 4
0
        public void SilentAuthStrategyFallbackTest()
        {
            using (var harness = CreateTestHarness())
            {
                //SilentRequest should always get an exception from the local client strategy and use the broker strategy instead when the right error codes
                //are thrown.

                // Arrange
                var mockBroker      = Substitute.For <IBroker>();
                var expectedAccount = Substitute.For <IAccount>();
                mockBroker.GetAccountsAsync(TestConstants.ClientId, TestConstants.RedirectUri).Returns(new[] { expectedAccount });
                mockBroker.IsBrokerInstalledAndInvokable().Returns(false);

                var platformProxy = Substitute.For <IPlatformProxy>();
                platformProxy.CanBrokerSupportSilentAuth().Returns(true);
                platformProxy.CreateBroker(null).Returns(mockBroker);


                var mockClientStrategy             = Substitute.For <ISilentAuthRequestStrategy>();
                var mockBrokerStrategy             = Substitute.For <ISilentAuthRequestStrategy>();
                var mockBrokerAuthenticationResult = Substitute.For <AuthenticationResult>();

                var invlidGrantException = new MsalException(MsalError.InvalidGrantError);
                var NoAccountException   = new MsalException(MsalError.NoAccountForLoginHint);
                var NoTokensException    = new MsalException(MsalError.NoTokensFoundError);

                var response = new MsalTokenResponse
                {
                    IdToken       = MockHelpers.CreateIdToken(TestConstants.UniqueId, TestConstants.DisplayableId),
                    AccessToken   = "access-token",
                    ClientInfo    = MockHelpers.CreateClientInfo(),
                    ExpiresIn     = 3599,
                    CorrelationId = "correlation-id",
                    RefreshToken  = "refresh-token",
                    Scope         = TestConstants.s_scope.AsSingleString(),
                    TokenType     = "Bearer"
                };

                mockBrokerStrategy.ExecuteAsync(new CancellationToken()).Returns(mockBrokerAuthenticationResult);
                mockClientStrategy.ExecuteAsync(new CancellationToken()).Throws(invlidGrantException);

                //Execute silent request with invalid grant
                var silentRequest = new SilentRequest(harness.ServiceBundle, _parameters, _acquireTokenSilentParameters, mockClientStrategy, mockBrokerStrategy);
                var result        = silentRequest.ExecuteTestAsync(new CancellationToken());
                Assert.AreEqual(result, mockBrokerAuthenticationResult);

                //Execute silent request with no accounts exception
                mockClientStrategy.ExecuteAsync(new CancellationToken()).Throws(NoAccountException);
                silentRequest = new SilentRequest(harness.ServiceBundle, _parameters, _acquireTokenSilentParameters, mockClientStrategy, mockBrokerStrategy);
                result        = silentRequest.ExecuteTestAsync(new CancellationToken());
                Assert.AreEqual(result, mockBrokerAuthenticationResult);

                //Execute silent request with no tokens exception
                mockClientStrategy.ExecuteAsync(new CancellationToken()).Throws(NoTokensException);
                silentRequest = new SilentRequest(harness.ServiceBundle, _parameters, _acquireTokenSilentParameters, mockClientStrategy, mockBrokerStrategy);
                result        = silentRequest.ExecuteTestAsync(new CancellationToken());
                Assert.AreEqual(result, mockBrokerAuthenticationResult);
            }
        }
        public void ExceptionsArePubliclyCreatable_MsalException()
        {
            var innerEx = new InvalidOperationException();
            var ex      = new MsalException("code1", "msg1", innerEx);

            Assert.AreEqual("code1", ex.ErrorCode);
            Assert.AreEqual("msg1", ex.Message);
            Assert.AreSame(innerEx, ex.InnerException);
        }
Ejemplo n.º 6
0
        public void Exception_ToString()
        {
            var           innerException = new InvalidOperationException("innerMsg");
            MsalException ex             = new MsalException("errCode", "errMessage", innerException);

            Assert.IsTrue(ex.ToString().Contains("errCode"));
            Assert.IsTrue(ex.ToString().Contains("errMessage"));
            Assert.IsTrue(ex.ToString().Contains("innerMsg"));
        }
        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");
        }
        private static void DisplayInnerException(MsalException ex)
        {
            string message = ex.Message;

            if (ex.InnerException != null)
            {
                message += "Inner Exception : " + ex.InnerException.Message;
            }
            MessageBox.Show(message);
        }
        public async Task LoginPage_OnLoginClickedAsync_Cancelled()
        {
            var mocks = new LoginPageControllerMocks();

            MockForms.Init();
            var mainPage  = new MainPage();
            var loginPage = new LoginPage();
            var sequence  = new MockSequence();

            mocks.CreateLoginPage.InSequence(sequence).Setup(c => c()).Returns(loginPage);
            mocks.LrpNavigation.InSequence(sequence).Setup(n => n.PushModalAsync(loginPage)).Returns(Task.CompletedTask);
            var cancelledException = new MsalException(LrpConstants.AuthenticationCanceledErrorCode);

            mocks.JwtTokenManager.InSequence(sequence).Setup(j => j.RequestLoginAsync()).Throws(cancelledException);
            BuildController(mocks, mainPage);
            await mainPage.OnAppearingAsync();

            await loginPage.OnLoginClickedAsync();
        }
Ejemplo n.º 10
0
        private void SerializeDeserializeAndValidate(MsalException ex, Type expectedType, bool isServiceExceptionDerived)
        {
            string json = ex.ToJsonString();

            var exDeserialized = MsalException.FromJsonString(json);

            Assert.AreEqual(expectedType, exDeserialized.GetType());
            Assert.AreEqual(ex.ErrorCode, exDeserialized.ErrorCode);
            Assert.AreEqual(ex.Message, exDeserialized.Message);

            if (isServiceExceptionDerived)
            {
                var svcEx = (MsalServiceException)exDeserialized;

                Assert.AreEqual(SomeClaims, svcEx.Claims);
                Assert.AreEqual(SomeResponseBody, svcEx.ResponseBody);
                Assert.AreEqual(SomeCorrelationId, svcEx.CorrelationId);
                Assert.AreEqual(SomeSubError, svcEx.SubError);
            }
        }
        private void CreateException(Exception ex)
        {
            string        output    = string.Empty;
            MsalException exception = ex as MsalException;

            if (exception != null)
            {
                output += string.Format("Error Code - {0}" + Environment.NewLine + "Message - {1}" + Environment.NewLine, exception.ErrorCode, exception.Message);
                if (exception is MsalServiceException)
                {
                    output += string.Format("Status Code - {0}" + Environment.NewLine, ((MsalServiceException)exception).StatusCode);
                    output += string.Format("Claims - {0}" + Environment.NewLine, ((MsalServiceException)exception).Claims);
                    output += string.Format("Raw Response - {0}" + Environment.NewLine, ((MsalServiceException)exception).ResponseBody);
                }
            }
            else
            {
                output = ex.Message + Environment.NewLine + ex.StackTrace;
            }

            void EnsureUIThreadSync() => callResult.Text = output;

            this.RenderActionOnUIThread(EnsureUIThreadSync);
        }
Ejemplo n.º 12
0
 public AuthorizationTokenException(MsalException exception)
 {
     this.exception = exception;
 }
Ejemplo n.º 13
0
        public bool Authenticate(bool throwOnError = false, string resource = ManagementAzureCom, bool prompt = false)
        {
            Log.Debug("azure ad:enter");
            _resource = resource;

            if (_tokenExpirationHalfLife > DateTime.Now)
            {
                Log.Debug("token still valid");
                return(false);
            }
            else if (!IsAuthenticated)
            {
                Log.Info("authenticating to azure", ConsoleColor.Green);
            }
            else
            {
                Log.Warning($"refreshing aad token. token expiration half life: {_tokenExpirationHalfLife}");
            }

            try
            {
                if (string.IsNullOrEmpty(Config.AzureTenantId))
                {
                    Config.AzureTenantId = _commonTenantId;
                }

                if (Config.IsClientIdConfigured())
                {
                    // no prompt with clientid and secret
                    _confidentialClientApp = ConfidentialClientApplicationBuilder
                                             .CreateWithApplicationOptions(new ConfidentialClientApplicationOptions
                    {
                        ClientId     = Config.AzureClientId,
                        RedirectUri  = resource,
                        ClientSecret = Config.AzureClientSecret,
                        TenantId     = Config.AzureTenantId,
                        ClientName   = Config.AzureClientId
                    })
                                             .WithAuthority(AzureCloudInstance.AzurePublic, Config.AzureTenantId)
                                             .WithLogging(MsalLoggerCallback, LogLevel.Verbose, true, true)
                                             .Build();

                    if (Scopes.Count < 1)
                    {
                        Scopes = _defaultScope;
                    }

                    foreach (string scope in Scopes)
                    {
                        TokenCacheHelper.EnableSerialization(_confidentialClientApp.AppTokenCache);
                        AuthenticationResult = _confidentialClientApp
                                               .AcquireTokenForClient(new List <string>()
                        {
                            scope
                        })
                                               .ExecuteAsync().Result;
                        Log.Debug($"scope authentication result:", AuthenticationResult);
                    }
                }
                else
                {
                    _publicClientApp = PublicClientApplicationBuilder
                                       .Create(_wellKnownClientId)
                                       .WithAuthority(AzureCloudInstance.AzurePublic, Config.AzureTenantId)
                                       .WithLogging(MsalLoggerCallback, LogLevel.Verbose, true, true)
                                       .WithDefaultRedirectUri()
                                       .Build();

                    TokenCacheHelper.EnableSerialization(_publicClientApp.UserTokenCache);
                    AuthenticationResult = _publicClientApp
                                           .AcquireTokenSilent(_defaultScope, _publicClientApp.GetAccountsAsync().Result.FirstOrDefault())
                                           .ExecuteAsync().Result;

                    if (Scopes.Count > 0)
                    {
                        Log.Info($"adding scopes {Scopes.Count}");
                        AuthenticationResult = _publicClientApp
                                               .AcquireTokenSilent(Scopes, _publicClientApp.GetAccountsAsync().Result.FirstOrDefault())
                                               .ExecuteAsync().Result;
                    }
                }

                BearerToken = AuthenticationResult.AccessToken;
                long tickDiff = ((AuthenticationResult.ExpiresOn.ToLocalTime().Ticks - DateTime.Now.Ticks) / 2) + DateTime.Now.Ticks;
                _tokenExpirationHalfLife = new DateTimeOffset(new DateTime(tickDiff));

                Log.Info($"authentication result:", ConsoleColor.Green, null, AuthenticationResult);
                Log.Highlight($"aad token expiration: {AuthenticationResult.ExpiresOn.ToLocalTime()}");
                Log.Highlight($"aad token half life expiration: {_tokenExpirationHalfLife}");

                _timer          = new Timer(Reauthenticate, null, Convert.ToInt32((_tokenExpirationHalfLife - DateTime.Now).TotalMilliseconds), Timeout.Infinite);
                IsAuthenticated = true;

                return(true);
            }
            catch (MsalUiRequiredException)
            {
                if (!Config.IsClientIdConfigured())
                {
                    AuthenticationResult = _publicClientApp
                                           .AcquireTokenInteractive(_defaultScope)
                                           .ExecuteAsync().Result;
                    return(Authenticate(throwOnError, resource, true));
                }

                if (throwOnError)
                {
                    throw;
                }

                IsAuthenticated = false;
                return(false);
            }
            catch (AggregateException ae)
            {
                Log.Exception($"aggregate exception:{ae}");

                if (ae.GetBaseException() is MsalException)
                {
                    MsalException me = ae.GetBaseException() as MsalException;
                    Log.Exception($"msal exception:{me}");

                    if (me.ErrorCode.Contains("interaction_required") && !prompt)
                    {
                        return(Authenticate(throwOnError, resource, true));
                    }
                }

                return(false);
            }
            catch (Exception e)
            {
                Log.Exception($"{e}");

                if (throwOnError)
                {
                    throw;
                }

                IsAuthenticated = false;
                return(false);
            }
        }
        private static async Task<AuthenticationParameters> CreateFromResourceUrlCommonAsync(Uri resourceUrl)
        {
            if (resourceUrl == null)
            {
                throw new ArgumentNullException("resourceUrl");
            }

            AuthenticationParameters authParams;

            try
            {
                HttpClientWrapper request = new HttpClientWrapper(resourceUrl.AbsoluteUri, null);
                using (await request.GetResponseAsync().ConfigureAwait(false))
                {
                    var ex = new MsalException(MsalError.UnauthorizedResponseExpected);
                    PlatformPlugin.Logger.Error(null, ex);
                    throw ex;                    
                }
            }
            catch (HttpRequestWrapperException ex)
            {
                PlatformPlugin.Logger.Error(null, ex);
                IHttpWebResponse response = ex.WebResponse;
                if (response == null)
                {
                    var serviceEx = new MsalServiceException(MsalErrorMessage.UnauthorizedHttpStatusCodeExpected, ex);
                    PlatformPlugin.Logger.Error(null, serviceEx);
                    throw serviceEx;
                }

                authParams = CreateFromUnauthorizedResponseCommon(response);
                
            }

            return authParams;
        }
Ejemplo n.º 15
0
        public void MsalExceptionCanSerializeAndDeserializeRoundTrip()
        {
            var ex = new MsalException(SomeErrorCode, SomeErrorMessage);

            SerializeDeserializeAndValidate(ex, typeof(MsalException), false);
        }