public async Task ResetPassword_CallWithMockedIAuthentication_ThrowsAndCatchesAuthenticationException() { // Arrange var mock = new Mock <IAuthentication>(); var resetPasswordDto = new ResetPasswordDto() { NewPassword = "******", ConfirmNewPassword = "******", ValidationToken = "token", }; string exceptionMessage = "ExceptionThrown"; var ex = new AuthenticationException(exceptionMessage); mock.Setup(auth => auth.ResetPassword(resetPasswordDto)).ThrowsAsync(ex); var authController = new AuthController(mock.Object); // Act var result = await authController.ResetPassword(resetPasswordDto); var response = (BadRequestObjectResult)result; var objectResult = (ResponseDto <ErrorDto>)response.Value; // Assert Assert.Equal(exceptionMessage, objectResult.Data.Message); }
public async Task Login_CallWithMockedIAuthentication_ThrowsAndCatchesAuthenticationException() { // Arrange var mock = new Mock <IAuthentication>(); var loginDto = new LoginDto() { Email = "*****@*****.**", Password = "******", }; string exceptionMessage = "ExceptionThrown"; var ex = new AuthenticationException(exceptionMessage); mock.Setup(auth => auth.LoginUserAsync(loginDto)).ThrowsAsync(ex); var authController = new AuthController(mock.Object); // Act var result = await authController.Login(loginDto); var response = (BadRequestObjectResult)result; var objectResult = (ResponseDto <ErrorDto>)response.Value; // Assert Assert.Equal(exceptionMessage, objectResult.Data.Message); }
public async Task Register_CallWithMockedIAuthentication_ThrowsAndCatchesAuthenticationException() { // Arrange var mock = new Mock <IAuthentication>(); var registrationDto = new RegistrationDto() { Username = "******", Email = "*****@*****.**", Password = "******", PasswordConfirmation = "password", Locale = "en-US", Timezone = "Asia/Calcutta", }; string exceptionMessage = "ExceptionThrown"; var ex = new AuthenticationException(exceptionMessage); mock.Setup(auth => auth.RegisterUserAsync(registrationDto)).ThrowsAsync(ex); var authController = new AuthController(mock.Object); // Act var result = await authController.Register(registrationDto); var response = (BadRequestObjectResult)result; var objectResult = (ResponseDto <ErrorDto>)response.Value; // Assert Assert.Equal(exceptionMessage, objectResult.Data.Message); }
private void AuthenticateOnCluster(Connection connection) { // try once if (TryAuthenticateOnCluster(connection)) { return; } // if it fails, maybe we need to reset the credential factory, // which may be caching credentials, to restart it all? if (_client.CredentialsFactory is IResettableCredentialsFactory resettableFactory) { // reset resettableFactory.Reset(); // try again if (TryAuthenticateOnCluster(connection)) { return; } } // fail var authException = new AuthenticationException("Invalid credentials!"); connection.Close("Failed to authenticate connection", authException); throw authException; }
public void AuthExceptionWithNullInnerException() { AuthenticationException authExToBeThrown = null; string authError = "Error Occured"; try { ClientCredential cc = new ClientCredential("SomeClientId", "SomethingSomething"); ActiveDirectoryServiceSettings adSvcSettings = new ActiveDirectoryServiceSettings() { AuthenticationEndpoint = new Uri("https://randomEndPoint"), TokenAudience = new Uri("https://SomeUri"), ValidateAuthority = true }; var token = ApplicationTokenProvider.LoginSilentAsync("SomeDomain", cc, adSvcSettings).GetAwaiter().GetResult(); } catch (AdalException adalEx) { authExToBeThrown = new AuthenticationException(authError); } Assert.NotNull(authExToBeThrown); Assert.Equal(authError, authExToBeThrown.Message); }
public static void RunClient(string machineName, string serverName) { TcpClient tcpClient = new TcpClient(machineName, 443); Console.WriteLine("Client connected."); SslStream sslStream = new SslStream((Stream)tcpClient.GetStream(), false, new RemoteCertificateValidationCallback(SslTcpClient.ValidateServerCertificate), (LocalCertificateSelectionCallback)null); try { sslStream.AuthenticateAsClient(serverName); } catch (AuthenticationException ex) { ProjectData.SetProjectError((Exception)ex); AuthenticationException authenticationException = ex; Console.WriteLine("Exception: {0}", (object)authenticationException.Message); if (authenticationException.InnerException != null) { Console.WriteLine("Inner exception: {0}", (object)authenticationException.InnerException.Message); } Console.WriteLine("Authentication failed - closing the connection."); tcpClient.Close(); ProjectData.ClearProjectError(); return; } byte[] bytes = Encoding.UTF8.GetBytes("Hello from the client.<EOF>"); sslStream.Write(bytes); sslStream.Flush(); Console.WriteLine("Server says: {0}", (object)SslTcpClient.ReadMessage(sslStream)); tcpClient.Close(); Console.WriteLine("Client closed."); }
private Task HandleUserAuthenticationExceptionAsync(HttpContext context, AuthenticationException exception) { context.Response.ContentType = "application/json"; context.Response.StatusCode = 401; return(context.Response.WriteAsync(exception.ToString())); }
public void OnBehalfOfProvider_ConstructorShouldThrowExceptionWithNullConfidentialClientApp() { AuthenticationException ex = Assert.ThrowsException <AuthenticationException>(() => new OnBehalfOfProvider(null, _scopes)); Assert.AreEqual(ex.Error.Code, ErrorConstants.Codes.InvalidRequest, "Invalid exception code."); Assert.AreEqual(ex.Error.Message, string.Format(ErrorConstants.Message.NullValue, "confidentialClientApplication"), "Invalid exception message."); }
/// <summary> /// Add service exception message info to message window /// </summary> internal static string AddServiceMessageWithDetail(string service, Exception ex) { string detailString = string.Empty; // NOTE tgoryagina: Fix CR147546. if (string.Equals(service, VRP_ROUTING_STRING)) { service = ROUTING_STRING; } if (ex is AuthenticationException) { AuthenticationException exAuthentication = ex as AuthenticationException; string format = (string)App.Current.FindResource("ServiceAuthError"); detailString = string.Format(format, service, exAuthentication.ServiceName); } else if (ex is CommunicationException) { string format = (string)App.Current.FindResource("ServiceConnectionError"); string msg = string.Format(format, service); detailString = FormatCommunicationError(msg, ex as CommunicationException); } return(detailString); }
public void ConstructorShouldThrowExceptionWithNullConfidentialClientApp() { AuthenticationException ex = Assert.Throws <AuthenticationException>(() => new ClientCredentialProvider(null)); Assert.Equal(ex.Error.Code, ErrorConstants.Codes.InvalidRequest); Assert.Equal(ex.Error.Message, String.Format(ErrorConstants.Message.NullValue, "confidentialClientApplication")); }
private void CreateSSLStream(String host, TcpClient socket, X509Certificate certificate) { try { //Initializes a new instance of the SslStream class using the specified Stream, stream closure behavior, certificate validation delegate and certificate selection delegate SslStream sslStream = new SslStream(socket.GetStream(), false, ValidateServerCertificate, LocalCertificateSelection); X509CertificateCollection certCol = new X509CertificateCollection(); certCol.Add(certificate); sslStream.AuthenticateAsClient(host, certCol, SslProtocols.Default, true); Stream = sslStream; } catch (AuthenticationException e) { log.Warn("Exception: {0}", e.Message); if (e.InnerException != null) { log.Warn("Inner exception: {0}", e.InnerException.Message); e = new AuthenticationException(e.InnerException.Message, e.InnerException); } socket.Close(); throw new TransportException(string.Format("Authentication failed, closing connection to broker: {0}", e.Message)); } }
// Detects of any exceptions have occured and throws the appropriate exceptions. internal void detectError() { ResponseException exception = null; if (statusCode >= 500) { exception = new ServerException(this); } else if (statusCode == 404) { exception = new NotFoundException(this); } else if (statusCode == 401) { exception = new AuthenticationException(this); } else if (statusCode >= 400) { exception = new ClientException(this); } else if (!parsed) { exception = new ParserException(this); } if (exception != null) { throw exception; } }
public static Neo4jException ParseServerException(string code, string message) { Neo4jException error; var parts = code.Split('.'); var classification = parts[1].ToLowerInvariant(); switch (classification) { case "clienterror": if (AuthenticationException.IsAuthenticationError(code)) { error = new AuthenticationException(message); } else if (ProtocolException.IsProtocolError(code)) { error = new ProtocolException(code, message); } else { error = new ClientException(code, message); } break; case "transienterror": error = new TransientException(code, message); break; default: error = new DatabaseException(code, message); break; } return(error); }
public void TestSerialization() { var expected = new AuthenticationException("Bad boys, bad boys. Whatcha gonna do?", new Exception("InnerException")); using (var stream = new MemoryStream()) { var formatter = new BinaryFormatter(); formatter.Serialize(stream, expected); stream.Position = 0; var ex = (AuthenticationException)formatter.Deserialize(stream); Assert.AreEqual(expected.Message, ex.Message, "Unexpected Message."); } expected = new AuthenticationException("Bad boys, bad boys. Whatcha gonna do?"); using (var stream = new MemoryStream()) { var formatter = new BinaryFormatter(); formatter.Serialize(stream, expected); stream.Position = 0; var ex = (AuthenticationException)formatter.Deserialize(stream); Assert.AreEqual(expected.Message, ex.Message, "Unexpected Message."); } expected = new AuthenticationException(); using (var stream = new MemoryStream()) { var formatter = new BinaryFormatter(); formatter.Serialize(stream, expected); stream.Position = 0; var ex = (AuthenticationException)formatter.Deserialize(stream); Assert.AreEqual(expected.Message, ex.Message, "Unexpected Message."); } }
public async Task ShouldPropagateSecurityException() { var error = new AuthenticationException("Procedure not found"); var uri = new Uri("neo4j://123:456"); var routingTable = new RoutingTable(null, new List <Uri> { uri }); var poolManagerMock = new Mock <IClusterConnectionPoolManager>(); poolManagerMock.Setup(x => x.CreateClusterConnectionAsync(uri)) .ReturnsAsync(new Mock <IConnection>().Object); var discovery = new Mock <IDiscovery>(); discovery.Setup(x => x.DiscoverAsync(It.IsAny <IConnection>(), "", null, Bookmark.Empty)).Throws(error); var logger = new Mock <ILogger>(); logger.Setup(x => x.Error(It.IsAny <Exception>(), It.IsAny <string>(), It.IsAny <object[]>())); var manager = NewRoutingTableManager(routingTable, poolManagerMock.Object, discovery.Object, logger: logger.Object); var exc = await Record.ExceptionAsync(() => manager.UpdateRoutingTableAsync(routingTable, AccessMode.Read, "", null, Bookmark.Empty)); exc.Should().Be(error); logger.Verify(x => x.Error(error, It.IsAny <string>(), It.IsAny <object[]>())); }
private static Task HandleExceptionAsync(HttpContext context, Exception ex, ILogger logger) { // throw ex; var code = ex switch { NotFoundException _ => HttpStatusCode.NotFound, InvalidCredentialException _ => HttpStatusCode.Forbidden, AuthenticationException _ => HttpStatusCode.Unauthorized, InvalidStateException _ => HttpStatusCode.BadRequest, IllegalArgumentException _ => HttpStatusCode.BadRequest, _ => HttpStatusCode.InternalServerError }; var logErrMsg = $"{ex.Message} - {context.Request.Path}{context.Request.QueryString}"; if (code == HttpStatusCode.InternalServerError) { logger.LogError(logErrMsg); } else { logger.LogInformation(logErrMsg); } var result = JsonConvert.SerializeObject(new { error = ex.Message }); context.Response.ContentType = "application/json"; context.Response.StatusCode = (int)code; return(context.Response.WriteAsync(result)); } }
public void IntegratedWindows_ConstructorShouldThrowExceptionWithNullPublicClientApp() { AuthenticationException ex = Assert.ThrowsException <AuthenticationException>(() => new IntegratedWindowsAuthenticationProvider(null, _scopes)); Assert.AreEqual(ex.Error.Code, ErrorConstants.Codes.InvalidRequest, "Invalid exception code."); Assert.AreEqual(ex.Error.Message, string.Format(ErrorConstants.Message.NullValue, "publicClientApplication"), "Invalid exception message."); }
void ValidateRequest(RecordRewardRequest request) { User user = userRepository.TryGet(request.Username)?.ToServiceModel(); if (user is null) { AuthenticationException ex = new AuthenticationException("The provided user is not registered"); logger.Error( MyOperation.RecordReward, OperationStatus.Failure, ex, new LogInfo(MyLogInfoKey.User, request.Username)); throw ex; } bool isTokenValid = requestHmacEncoder.IsTokenValid(request.HmacToken, request, user.SharedSecretKey); if (!isTokenValid) { AuthenticationException ex = new AuthenticationException("The provided HMAC token is not valid"); logger.Error( MyOperation.RecordReward, OperationStatus.Failure, ex, new LogInfo(MyLogInfoKey.User, request.Username), new LogInfo(MyLogInfoKey.GiveawaysProvider, request.GiveawaysProvider), new LogInfo(MyLogInfoKey.GiveawayId, request.GiveawayId)); throw ex; } }
// Detects of any exceptions have occured and throws the appropriate exceptions. protected internal virtual void DetectError(HTTPClient client) { ResponseException exception = null; string reason = string.Format("{0} {1}", StatusCode, ReasonPhrase); if (StatusCode >= 500) { exception = new ServerException(this, new Exception(reason)); } else if (StatusCode == 404) { exception = new NotFoundException(this, new Exception(reason)); } else if (StatusCode == 401) { exception = new AuthenticationException(this, new Exception(reason)); } else if (StatusCode >= 400) { exception = new ClientException(this, new Exception(reason)); } else if (!Parsed) { exception = new ParserException(this, new Exception(reason)); } if (exception != null) { exception.Log(client.Configuration, this); throw exception; } }
public void ShouldReturnKeys() { var failure = new AuthenticationException("unauthenticated"); var cursor = CreateFailingResultCursor(failure, 2, 5); var result = new RxResult(Observable.Return(cursor)); VerifyKeys(result, "key01", "key02"); }
public void ToGraphUserAccount_ShouldThrowExceptionWhenClaimsPrincipalHasNoClaims() { ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(); AuthenticationException authException = Assert.ThrowsException <AuthenticationException>(() => claimsPrincipal.ToGraphUserAccount()); Assert.AreEqual(ErrorConstants.Codes.InvalidClaim, authException.Error.Code, "Unexpected error code set."); Assert.AreEqual(string.Format(ErrorConstants.Message.MissingClaim, AuthConstants.ClaimTypes.ObjectIdUriSchema), authException.Error.Message, "Unexpected error message set."); }
public void ToGraphUserAccount_ShouldThrowExceptionWhenClaimsPrincipalIsNull() { ClaimsPrincipal claimsPrincipal = null; AuthenticationException authException = Assert.ThrowsException <AuthenticationException>(() => claimsPrincipal.ToGraphUserAccount()); Assert.AreEqual(ErrorConstants.Codes.InvalidRequest, authException.Error.Code, "Unexpected error code set."); Assert.AreEqual(string.Format(ErrorConstants.Message.NullValue, "claimsPrincipal"), authException.Error.Message, "Unexpected error message set."); }
public async Task DeviceClient_SendAsyncInvalidServiceCertificateMqttWs_Fails() { Client.TransportType transport = Client.TransportType.Mqtt_WebSocket_Only; AuthenticationException exception = await Assert.ThrowsExceptionAsync <AuthenticationException>( () => TestDeviceClientInvalidServiceCertificate(transport)).ConfigureAwait(false); Assert.IsInstanceOfType(exception.InnerException.InnerException.InnerException, typeof(AuthenticationException)); }
/// <summary> /// Extension method that generates problem details for the exception. /// </summary> /// <param name="source">The exception to map to a <see cref="ProblemDetails"/></param> /// <param name="controller">The base controller the exception occured in. </param> /// <param name="type">Optional parameter that sets the URL for the human readable explanation for the status code. Default value is set to https://httpstatuses.com/403 </param> /// <param name="status">Optional parameter that sets the return status code for the problem. Default value is set to 403.</param> /// <param name="title">Optional parameter that sets the title for the problem. Default value is set to Forbidden.</param> /// <returns>Instance of the problem details.</returns> public static ProblemDetails GetProblemDetails(this AuthenticationException source, ControllerBase controller, string type = "https://httpstatuses.com/401", int?status = 401, string title = "UnAuthorized") { return(new ProblemDetails { Type = type, Status = status, Title = title, Instance = controller?.HttpContext?.Request?.Path, Detail = source?.Message }); }
public void Constructor_String_PassedInMessageCorrect() { const string passedInMessage = "base was called"; AuthenticationException authenticationException = new AuthenticationException(passedInMessage); Assert.Equal(passedInMessage, authenticationException.Message); }
private string getAuthenticationExceptionEventId(TicketException e) { AuthenticationException authEx = this.getAuthenticationExceptionAsCause(e); //if (this.logger.isDebugEnabled()) // this.logger.debug("An authentication error has occurred. Returning the event id " + authEx.getType()); return(authEx.getType()); }
public void Decode_ShouldThrowExceptionWhenInvalidJWTokenPayloadIsSet() { string validToken = "eyJ0eXAiOiJKV1QiLCJub25jZSI6IkFBMjMyVEVTVCIsImFsZyI6IkhTMjU2In0.eyJmYW1pbHlfbmFtZSI6IkRvZSIsImdpdmVuX25hbWUiOiJKb2huIiwibmFtZSI6IkpvaG4gRG9lIiwib2lkIjoiZTYwMmFkYTctNmVmZC00ZTE4LWE5NzktNjNjMDJiOWYzYzc2Iiwic2NwIjoiVXNlci5SZWFkQmFzaWMuQWxsIiwidGlkIjoiNmJjMTUzMzUtZTJiOC00YTlhLTg2ODMtYTUyYTI2YzhjNTgzIiwidW5pcXVlX25hbWUiOiJqb2huQGRvZS50ZXN0LmNvbSIsInVwbiI6ImpvaG5AZG9lLnRlc3QuY29tIn0.hf9xI5XYBjGec - 4n4_Kxj8Nd2YHBtihdevYhzFxbpXQ"; AuthenticationException exception = Assert.ThrowsException <AuthenticationException>(() => JwtHelpers.DecodeToObject <JwtPayload>(validToken)); Assert.AreEqual(exception.Error.Code, ErrorConstants.Codes.InvalidJWT); Assert.AreEqual(exception.Error.Message, ErrorConstants.Message.InvalidJWT); }
public void ShouldReturnKeysEvenAfterFailedSummary() { var failure = new AuthenticationException("unauthenticated"); var cursor = CreateFailingResultCursor(failure, 2, 5); var result = new RxResult(Observable.Return(cursor)); VerifyError(result.Consume(), failure); VerifyKeys(result, "key01", "key02"); }
public void ShouldThrowExceptionWhenScopesAreEmpty() { var mock = Mock.Of <IPublicClientApplication>(); AuthenticationException ex = Assert.Throws <AuthenticationException>(() => new IntegratedWindowsAuthenticationProvider(mock, Enumerable.Empty <string>())); Assert.Equal(ex.Error.Message, ErrorConstants.Message.EmptyScopes); Assert.Equal(ex.Error.Code, ErrorConstants.Codes.InvalidRequest); }
internal static AuthenticationException CreateCustomException(string uri, AuthenticationException ex) { if (uri.StartsWith("https")) { return(new AuthenticationException( string.Format("Invalid remote SSL certificate, overide with: \nServicePointManager.ServerCertificateValidationCallback += ((sender, certificate, chain, sslPolicyErrors) => isValidPolicy);"), ex)); } return(null); }
internal static AuthenticationException CreateCustomException(string uri, AuthenticationException ex) { if (uri.StartsWith("https")) { return new AuthenticationException( string.Format("Invalid remote SSL certificate, overide with: \nServicePointManager.ServerCertificateValidationCallback += ((sender, certificate, chain, sslPolicyErrors) => isValidPolicy);"), ex); } return null; }
private async Task<bool> GetSessionCookieAsync() { String result = await MakeOperationAsync(SupportedModules.NOMOD, SupportedMethods.Authenticate, forAuth: true); if (result.Equals(String.Empty)) { cookieCreation = DateTime.Now; return true; } else { LastException = new AuthenticationException("Authentication Fails"); return false; } }