public void TestSerializingExceptions() { using (var client = new Amazon.S3.AmazonS3Client()) { try { var fakeBucketName = "super.duper.fake.bucket.name.123." + Guid.NewGuid().ToString(); client.ListObjects(fakeBucketName); } catch (AmazonS3Exception e) { TestException(e); } var s3pue = CreateS3PostUploadException(); TestException(s3pue); var doe = CreateDeleteObjectsException(); TestException(doe); var aace = new AdfsAuthenticationControllerException("Message"); TestException(aace); #pragma warning disable 618 var ccre = new CredentialCallbackRequiredException("Message"); TestException(ccre); var afe = new AuthenticationFailedException("Message"); TestException(afe); #pragma warning restore 618 } }
public static void Handle(this AuthenticationFailedException e, HttpActionExecutedContext context) { var response = new HttpResponseMessage(); response.StatusCode = HttpStatusCode.Forbidden; context.Response = response; }
public static void Handle(this AuthenticationFailedException e, ExceptionContext context) { var viewResult = new ViewResult(); context.ExceptionHandled = true; viewResult.ViewName = "~/Views/Home/Login.cshtml"; viewResult.ViewBag.Message = Sentences.authenticationFailed; context.Result = viewResult; }
// Display details of the exception in a message dialog. // We are doing this here to help you, as a developer, understand exactly // what exception was received. In a real app, you would // handle exceptions within your code and give a more user-friendly behavior. internal static void DisplayException(AuthenticationFailedException exception) { var title = "Authentication failed"; StringBuilder content = new StringBuilder(); content.AppendLine("We were unable to connect to Office 365. Here's the exception we received:"); content.AppendFormat("Exception: {0}\n", exception.ErrorCode); content.AppendFormat("Description: {0}\n\n", exception.ErrorDescription); content.AppendLine("Suggestion: Make sure you have added the Connected Services to this project as outlined in the Readme file"); MessageDialogHelper.ShowDialogAsync(content.ToString(), title); Debug.WriteLine(content.ToString()); }
private bool TryParseUnknownAuthenticationException(AuthenticationFailedException exception, out string message) { var innerException = exception?.InnerException as MsalServiceException; bool isUnknownMsalServiceException = string.Equals(innerException?.ErrorCode, "access_denied", StringComparison.OrdinalIgnoreCase); message = null; if (isUnknownMsalServiceException) { StringBuilder messageBuilder = new StringBuilder(nameof(innerException.ErrorCode)); messageBuilder.Append(": ").Append(innerException.ErrorCode); message = messageBuilder.ToString(); } return(isUnknownMsalServiceException); }
public void RefreshTests_TryRefreshAsyncReturnsFalseForAuthenticationFailedException() { IConfigurationRefresher refresher = null; var mockResponse = new Mock <Response>(); var mockClient = new Mock <ConfigurationClient>(MockBehavior.Strict, TestHelpers.CreateMockEndpointString()); mockClient.SetupSequence(c => c.GetConfigurationSettingsAsync(It.IsAny <SettingSelector>(), It.IsAny <CancellationToken>())) .Returns(new MockAsyncPageable(_kvCollection)); var innerException = new AuthenticationFailedException("Authentication failed.") { Source = "Azure.Identity" }; mockClient.SetupSequence(c => c.GetConfigurationSettingAsync("TestKey1", It.IsAny <string>(), It.IsAny <CancellationToken>())) .Returns(Task.FromResult(Response.FromValue(_kvCollection.FirstOrDefault(s => s.Key == "TestKey1"), mockResponse.Object))) .Returns(Task.FromResult(Response.FromValue(_kvCollection.FirstOrDefault(s => s.Key == "TestKey1"), mockResponse.Object))) .Throws(new KeyVaultReferenceException(innerException.Message, innerException)); var config = new ConfigurationBuilder() .AddAzureAppConfiguration(options => { options.Client = mockClient.Object; options.Select("TestKey*"); options.ConfigureRefresh(refreshOptions => { refreshOptions.Register("TestKey1") .SetCacheExpiration(TimeSpan.FromSeconds(1)); }); refresher = options.GetRefresher(); }) .Build(); Assert.Equal("TestValue1", config["TestKey1"]); FirstKeyValue.Value = "newValue"; // Wait for the cache to expire Thread.Sleep(1500); // Second call to GetConfigurationSettingAsync does not throw Assert.True(refresher.TryRefreshAsync().Result); // Wait for the cache to expire Thread.Sleep(1500); // Third call to GetConfigurationSettingAsync throws KeyVaultReferenceException Assert.False(refresher.TryRefreshAsync().Result); }
public void SilentReauthenticateFailure() { try { // Setup InitializeSession(); var mockAzureCredentialFactory = new Mock <AzureCredentialFactory>(); mockAzureCredentialFactory.Setup(f => f.CreateSharedTokenCacheCredentials(It.IsAny <SharedTokenCacheCredentialOptions>())).Returns(() => new TokenCredentialMock( (times) => { if (times < 1) { return(new ValueTask <AccessToken>(new AccessToken(fakeToken, DateTimeOffset.Now.AddHours(1)))); } throw new CredentialUnavailableException("Exception from Azure Identity."); } )); AzureSession.Instance.RegisterComponent(nameof(AzureCredentialFactory), () => mockAzureCredentialFactory.Object, true); AzureSession.Instance.ClientFactory.AddHandler(new HttpMockHandler( (times) => { var response = new HttpResponseMessage(HttpStatusCode.Unauthorized) { Content = new StringContent(body401, Encoding.UTF8, "application/json"), }; response.Headers.Add("WWW-Authenticate", WwwAuthenticateIP); return(response); })); cmdlet.TenantId = Guid.NewGuid().ToString(); // Act cmdlet.InvokeBeginProcessing(); AuthenticationFailedException e = Assert.Throws <AuthenticationFailedException>(() => cmdlet.ExecuteCmdlet()); string errorMessage = $"Exception from Azure Identity.{Environment.NewLine}authorization_uri: https://login.windows.net/{Environment.NewLine}error: invalid_token{Environment.NewLine}error_description: Tenant IP Policy validate failed.{Environment.NewLine}claims: eyJhY2Nlc3NfdG9rZW4iOnsibmJmIjp7ImVzc2VudGlhbCI6dHJ1ZSwidmFsdWUiOiIxNjEzOTgyNjA2In0sInhtc19ycF9pcGFkZHIiOnsidmFsdWUiOiIxNjcuMjIwLjI1NS40MSJ9fX0={Environment.NewLine}"; Assert.Equal(errorMessage, e.Message); cmdlet.InvokeEndProcessing(); } finally { //Dispose AzureSessionInitializer.CreateOrReplaceSession(new MemoryDataStore()); } }
private bool IsUnableToOpenWebPageError(AuthenticationFailedException exception) { return(exception.InnerException is MsalClientException && ((MsalClientException)exception.InnerException)?.ErrorCode == MsalError.LinuxXdgOpen || (exception.Message?.ToLower()?.Contains("unable to open a web page") ?? false)); }
public static AuthenticationFailedException WithAdditionalMessage(this AuthenticationFailedException e, string additonal) { return(string.IsNullOrEmpty(additonal) ? e : new AuthenticationFailedException($"{e.Message}{Environment.NewLine}{additonal}", e)); }
public static Exception parseApiException(ApiException ex) { Exception exResponse = null; if (ex.Headers.Contains(ResponseNames.RESPONSE_HEADER_NAME)) { IEnumerable <string> values = ex.Headers.GetValues(ResponseNames.RESPONSE_HEADER_NAME); string responseName = values.First(); if (!String.IsNullOrEmpty(responseName)) { Debug.WriteLine(String.Format("Response Format: {0}", responseName)); switch (responseName) { // Parse Validation Error case ResponseNames.VALIDATION_ERROR_RESPONSE: exResponse = createDataInvalidException(ex); break; // Parse Alerts Not Found case ResponseNames.NO_ALERTS_FOUND_RESPONSE: exResponse = new NoAlertsFoundException() { Response = ex.GetContentAs <APIResponse <string> >() }; break; // Parse No Children Found case ResponseNames.NO_CHILDREN_FOUND_FOR_SELF_PARENT_RESPONSE: exResponse = new NoChildrenFoundException() { Response = ex.GetContentAs <APIResponse <string> >() }; break; // Parse Load Self Profile Error case ResponseNames.PARENT_NOT_FOUND_RESPONSE: exResponse = new LoadProfileFailedException() { Response = ex.GetContentAs <APIResponse <string> >() }; break; // Parse Upload File Exception case ResponseNames.FAILED_TO_UPLOAD_IMAGE_RESPONSE: exResponse = new UploadImageFailException() { Response = ex.GetContentAs <APIResponse <string> >() }; break; case ResponseNames.UPLOAD_FILE_IS_TOO_LARGE_RESPONSE: exResponse = new UploadFileIsTooLargeException() { Response = ex.GetContentAs <APIResponse <string> >() }; break; // Parse No Schools not found case ResponseNames.NO_SCHOOLS_FOUND_RESPONSE: exResponse = new NoSchoolsFoundException() { Response = ex.GetContentAs <APIResponse <string> >() }; break; // Parse Bad Credentials Response case ResponseNames.BAD_CREDENTIALS_RESPONSE: exResponse = new AuthenticationFailedException() { Response = ex.GetContentAs <APIResponse <string> >() }; break; case ResponseNames.ACCOUNT_DISABLED_RESPONSE: exResponse = new AccountDisabledException() { Response = ex.GetContentAs <APIResponse <string> >() }; break; case ResponseNames.ACCOUNT_LOCKED_RESPONSE: exResponse = new AccountLockedException() { Response = ex.GetContentAs <APIResponse <string> >() }; break; case ResponseNames.NO_NEW_ALERTS_FOUND_RESPONSE: exResponse = new NoNewAlertsFoundException() { Response = ex.GetContentAs <APIResponse <string> >() }; break; case ResponseNames.NO_ALERTS_BY_SON_FOUNDED_RESPONSE: exResponse = new NoAlertsFoundException() { Response = ex.GetContentAs <APIResponse <string> >() }; break; case ResponseNames.SOCIAL_MEDIA_BY_CHILD_NOT_FOUND_RESPONSE: exResponse = new NoSocialMediaFoundException() { Response = ex.GetContentAs <APIResponse <string> >() }; break; case ResponseNames.NO_ITERATIONS_FOUND_FOR_SELF_PARENT_RESPONSE: exResponse = new NoIterationsFoundForSelfParentException() { Response = ex.GetContentAs <APIResponse <string> >() }; break; case ResponseNames.EMAIL_ALREADY_EXISTS_RESPONSE: exResponse = new EmailAlreadyExistsException() { Response = ex.GetContentAs <APIResponse <string> >() }; break; case ResponseNames.NO_COMMENTS_EXTRACTED_RESPONSE: exResponse = new NoCommentsExtractedException() { Response = ex.GetContentAs <APIResponse <string> >() }; break; case ResponseNames.NO_LIKES_FOUND_IN_THIS_PERIOD_RESPONSE: exResponse = new NoLikesFoundInThisPeriodException() { Response = ex.GetContentAs <APIResponse <string> >() }; break; case ResponseNames.NO_ACTIVE_FRIENDS_IN_THIS_PERIOD_RESPONSE: exResponse = new NoActiveFriendsInThisPeriodException() { Response = ex.GetContentAs <APIResponse <string> >() }; break; case ResponseNames.NO_NEW_FRIENDS_AT_THIS_TIME_RESPONSE: exResponse = new NoNewFriendsInThisPeriodException() { Response = ex.GetContentAs <APIResponse <string> >() }; break; case ResponseNames.NO_ALERTS_STATISTICS_FOR_THIS_PERIOD_RESPONSE: exResponse = new NoAlertsStatisticsForThisPeriodException() { Response = ex.GetContentAs <APIResponse <string> >() }; break; case ResponseNames.SOCIAL_MEDIA_ACTIVITY_STATISTICS_NOT_FOUND_RESPONSE: exResponse = new SocialMediaActivityStatisticsNotFoundException() { Response = ex.GetContentAs <APIResponse <string> >() }; break; case ResponseNames.NO_SENTIMENT_ANALYSIS_STATISTICS_FOR_THIS_PERIOD_RESPONSE: exResponse = new NoSentimentAnalysisStatisticsForThisPeriodException() { Response = ex.GetContentAs <APIResponse <string> >() }; break; case ResponseNames.NO_COMMUNITY_STATISTICS_FOR_THIS_PERIOD_RESPONSE: exResponse = new NoCommunityStatisticsForThisPeriodException() { Response = ex.GetContentAs <APIResponse <string> >() }; break; case ResponseNames.NO_DIMENSIONS_STATISTICS_FOR_THIS_PERIOD_RESPONSE: exResponse = new NoDimensionsStatisticsForThisPeriodException() { Response = ex.GetContentAs <APIResponse <string> >() }; break; case ResponseNames.COMMENTS_BY_CHILD_NOT_FOUND_RESPONSE: exResponse = new NoCommentsBySonFoundException() { Response = ex.GetContentAs <APIResponse <string> >() }; break; case ResponseNames.ACCOUNT_PENDING_TO_BE_REMOVE_RESPONSE: exResponse = new AccountPendingToBeRemoveException() { Response = ex.GetContentAs <APIResponse <string> >() }; break; // Parse Generic Error case ResponseNames.GENERIC_ERROR_RESPONSE: exResponse = new GenericErrorException() { Response = ex.GetContentAs <APIResponse <string> >() }; break; } } } return(exResponse ?? ex); }
/// <summary>Create an IOE when an operation fails</summary> /// <param name="path">path of operation</param> /// <param name="operation">operation attempted</param> /// <param name="exception">caught the exception caught</param> /// <returns>an IOE to throw that contains the path and operation details.</returns> protected internal virtual IOException OperationFailure(string path, string operation , Exception exception, IList <ACL> acls) { IOException ioe; string aclList = "[" + RegistrySecurity.AclsToString(acls) + "]"; if (exception is KeeperException.NoNodeException) { ioe = new PathNotFoundException(path); } else { if (exception is KeeperException.NodeExistsException) { ioe = new FileAlreadyExistsException(path); } else { if (exception is KeeperException.NoAuthException) { ioe = new NoPathPermissionsException(path, "Not authorized to access path; ACLs: " + aclList); } else { if (exception is KeeperException.NotEmptyException) { ioe = new PathIsNotEmptyDirectoryException(path); } else { if (exception is KeeperException.AuthFailedException) { ioe = new AuthenticationFailedException(path, "Authentication Failed: " + exception + "; " + securityConnectionDiagnostics, exception); } else { if (exception is KeeperException.NoChildrenForEphemeralsException) { ioe = new NoChildrenForEphemeralsException(path, "Cannot create a path under an ephemeral node: " + exception, exception); } else { if (exception is KeeperException.InvalidACLException) { // this is a security exception of a kind // include the ACLs to help the diagnostics StringBuilder builder = new StringBuilder(); builder.Append("Path access failure ").Append(aclList); builder.Append(" "); builder.Append(securityConnectionDiagnostics); ioe = new NoPathPermissionsException(path, builder.ToString()); } else { ioe = new RegistryIOException(path, "Failure of " + operation + " on " + path + ": " + exception.ToString(), exception); } } } } } } } if (ioe.InnerException == null) { Sharpen.Extensions.InitCause(ioe, exception); } return(ioe); }