public bool Authenticate(Account account, string password, out AuthenticationError error) { if (account == null) { error = AuthenticationError.InvalidUsername; return(false); } error = AuthenticationError.None; var username = account.Username; if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password)) { error = AuthenticationError.InvalidInput; return(false); } var result = new PasswordHasher <Account>().VerifyHashedPassword(account, account.Password, password); if (result == PasswordVerificationResult.Failed) { error = AuthenticationError.InvalidPassword; return(false); } if (result == PasswordVerificationResult.SuccessRehashNeeded) { error = AuthenticationError.DatabaseError; return(false); } return(true); }
public void TestAdWordsApiExceptionForFault() { SoapFaultInspector <AdWordsApiException> inspector = new SoapFaultInspector <AdWordsApiException>() { ErrorType = typeof(ApiException) }; foreach (string faultXml in faultXmls) { XmlDocument xDoc = XmlUtilities.CreateDocument(faultXml); Message message = Message.CreateMessage(new XmlNodeReader(xDoc), Int32.MaxValue, TestMessageVersion); AdWordsApiException exception = Assert.Throws <AdWordsApiException>( delegate() { inspector.AfterReceiveReply(ref message, this.channel); }, "No exception was thrown for a SOAP Fault response"); Assert.AreEqual(typeof(ApiException), exception.ApiException.GetType()); ApiException apiException = (ApiException)exception.ApiException; Assert.AreEqual(1, apiException.errors.Length); Assert.AreEqual(typeof(AuthenticationError), apiException.errors[0].GetType()); AuthenticationError error = (AuthenticationError)apiException.errors[0]; Assert.AreEqual(AuthenticationErrorReason.CUSTOMER_NOT_FOUND, error.reason); } }
public void OnTokenFailure(AuthenticationError ex) { Activity.RunOnUiThread(() => { Activity.showMessage(ex.Message); Activity.displayAuthOptions(); }); }
public async Task Authenticate(string successUrl = null, string errorUrl = null, params Scope[] scopes) { Log.Debug("Authenticating with HSReplay.net..."); Authenticating?.Invoke(true); try { var data = await GetAuthData(successUrl ?? SuccessUrl, errorUrl ?? ErrorUrl); if (data == null) { Log.Error("Authentication failed, received no data"); AuthenticationError?.Invoke(AuthenticationErrorType.Unknown); return; } _data.Code = data.Code; _data.RedirectUrl = data.RedirectUrl; _data.TokenData = null; } catch (Exception e) { Log.Error(e); AuthenticationError?.Invoke(AuthenticationErrorType.Unknown); return; } Log.Debug("Authentication complete"); try { await UpdateToken(); Log.Debug("Claiming upload token if necessary"); if (_account.TokenStatus == TokenStatus.Unknown) { await _api.UpdateTokenStatus(); } if (_account.TokenStatus == TokenStatus.Unclaimed) { await ClaimUploadToken(_account.UploadToken); } Log.Debug("Updating account data"); if (!await UpdateAccountData()) { AuthenticationError?.Invoke(AuthenticationErrorType.AccountData); } } catch (Exception e) { AuthenticationError?.Invoke(AuthenticationErrorType.Unknown); Log.Error(e); } finally { Authenticating?.Invoke(false); Authenticated?.Invoke(); } }
public void GetErrorCode_ParsedCorrectly(string errorDescription, AuthenticationErrorCode?expectedResult) { // Arrange var authError = new AuthenticationError { ErrorDescription = errorDescription }; // Assert Assert.AreEqual(expectedResult, authError.ErrorCode); }
protected IActionResult HandleErrors <TData>(Response <TData> response, Func <TData, IActionResult> onSuccess) where TData : class { return(response.Match( error => error switch { AuthenticationError ae => Unauthorized(ae), AuthorizationError _ => Forbid(), ObjectAlreadyExistsError oaee => Conflict(oaee), ObjectNotFoundError onfe => NotFound(onfe), UserError ue => UnprocessableEntity(ue), ValidationError ve => BadRequest(ve), DomainError de => UnprocessableEntity(new { de.ExceptionType.Name, error.Message }), _ => StatusCode(StatusCodes.Status500InternalServerError, error) },
public IRestError GetError() { IRestError error; if (AuthenticationError.TryGetModel(GetModel(), out error)) { return(error); } if (ModelStateError.TryGetModel(GetModel(), out error)) { return(error); } return(new UnknownError(GetModel())); }
/// <summary> /// Handles the response to the <see cref="US.OpenServer.Protocols.WinAuth.WinAuthProtocolCommands.AUTHENTICATE"/> /// command packet. /// </summary> /// <remarks> /// <para> /// When an <see cref="US.OpenServer.Protocols.WinAuth.WinAuthProtocolCommands.AUTHENTICATED"/> /// response is received, notifies the <see cref="US.OpenServer.SessionBase"/> the /// client is authenticated enabling the session to allow execution of higher /// protocol layers. Finally, signals the <see cref="Authenticate(String, String, String)" /> /// function to unblock the calling thread. /// </para> /// <para> /// When an <see cref="US.OpenServer.Protocols.WinAuth.WinAuthProtocolCommands.ACCESS_DENIED"/> /// response is received, logs the error then signals the <see cref="Authenticate(String, String, String)" /> /// function to unblock the calling thread. /// </para> /// <para> /// When an <see cref="US.OpenServer.Protocols.WinAuth.WinAuthProtocolCommands.ERROR"/> /// response is received, logs the error then signals the <see cref="Authenticate(String, String, String)" /> /// function to unblock the calling thread. /// </para> /// <para> /// Prior to authentication the session disallows all protocols commands. /// </para> /// </remarks> /// <param name="br">A BinaryReader that contains the command packet.</param> public override void OnPacketReceived(BinaryReader br) { lock (this) { if (Session == null) { return; } WinAuthProtocolCommands command = (WinAuthProtocolCommands)br.ReadByte(); switch (command) { case WinAuthProtocolCommands.AUTHENTICATED: IsAuthenticated = true; Session.IsAuthenticated = true; AuthenticationSuccessful?.Invoke(Session.Address, Session.UserName); Log(Level.Info, "Authenticated."); Monitor.PulseAll(this); break; case WinAuthProtocolCommands.ACCESS_DENIED: AuthenticationFailed?.Invoke(Session.Address, Session.UserName); Log(Level.Notice, "Access denied."); Monitor.PulseAll(this); break; case WinAuthProtocolCommands.ERROR: { string errorMessage = br.ReadString(); AuthenticationError?.Invoke(Session.Address, Session.UserName, errorMessage); Log(Level.Notice, errorMessage); Monitor.PulseAll(this); break; } default: Log(Level.Error, string.Format("Invalid or unsupported command. Command: {0}", command)); break; } } }
public static async Task EnsureSuccessStatusCodeAsync(this HttpResponseMessage response) { if (response.IsSuccessStatusCode) { return; } string content = string.Empty; RegularErrorMessage regularErrorMessage = null; AuthenticationError authenticationError = null; if (response.Content != null) { try { content = await response.Content.ReadAsStringAsync().ConfigureAwait(false); try { regularErrorMessage = JsonConvert.DeserializeObject <RegularErrorMessage>(content); } catch (Exception) { authenticationError = JsonConvert.DeserializeObject <AuthenticationError>(content); } } catch (Exception) { } } if (regularErrorMessage != null) { throw new SpotifyHttpResponseWithRegularErrorException(response.StatusCode, response.Headers, content, regularErrorMessage.Error); } else if (authenticationError != null) { throw new SpotifyHttpResponseWithAuthenticationErrorException(response.StatusCode, response.Headers, content, authenticationError); } else { throw new SpotifyHttpResponseWithErrorCodeException(response.StatusCode, response.Headers, content); } }
/// <summary> /// Sends an HTTP request to the inner handler to send to the server as an asynchronous operation. /// </summary> /// <returns> /// Returns <see cref="T:System.Threading.Tasks.Task`1"/>. The task object representing the asynchronous operation. /// </returns> /// <param name="request">The HTTP request message to send to the server.</param><param name="cancellationToken">A cancellation token to cancel operation.</param><exception cref="T:System.ArgumentNullException">The <paramref name="request"/> was null.</exception> protected override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { /* If HttpContext.Current.User is authenticated, then return immediately. * This is typically the case when the application / IIS is configured to use * Windows integration with or without impersonation. * */ if (HttpContext.Current != null && HttpContext.Current.User != null && HttpContext.Current.User.Identity.IsAuthenticated) { return(base.SendAsync(request, cancellationToken)); } return(_AuthenticationProviders .FirstOrDefault(provider => provider.CanAuthenticate(request)) .ToMaybe() .ToServiceResponse(() => AuthenticationError.ProviderNotFound()) .Bind(provider => provider.Authenticate(request) .Fmap(principal => { // If we're hosted within IIS, set the HttpContext.Current.User if (HttpContext.Current != null) { HttpContext.Current.User = principal; } Thread.CurrentPrincipal = principal; return base.SendAsync(request, cancellationToken); })) .CatchAndContinue(error => { var completionSource = new TaskCompletionSource <HttpResponseMessage>(); completionSource.SetResult( request.CreateResponse( (HttpStatusCode)error.HttpStatusCode, new ErrorResponse <Unit>(error))); return new DataResponse <Task <HttpResponseMessage> >(completionSource.Task); }) .FromRight()); }
public static async Task TryAuthenticate(string successUrl = null, string errorUrl = null) { Authenticating?.Invoke(true); if (await HSReplayNetOAuth.Authenticate(successUrl, errorUrl)) { if (!await HSReplayNetOAuth.UpdateAccountData()) { ErrorManager.AddError("HSReplay.net Error", "Could not load HSReplay.net account status." + " Please try again later."); AuthenticationError?.Invoke(AuthenticationErrorType.AccountData); } await SyncCollection(); } else { ErrorManager.AddError("Could not authenticate with HSReplay.net", "Please try running HDT as administrator " + "(right-click the exe and select 'Run as administrator').\n" + "If that does not help please try again later.", true); AuthenticationError?.Invoke(AuthenticationErrorType.Authentication); } Authenticating?.Invoke(false); }
/// <summary> /// Initializes a new instance of the <see cref="IdokladAuthenticationException"/> class. /// </summary> /// <param name="authenticationError">Authentication error.</param> public IdokladAuthenticationException(AuthenticationError authenticationError) : base($"Authentication failed: {authenticationError?.Error}") { AuthenticationError = authenticationError; }
public static void IInitiatedAuthenticationError() { AuthenticationError?.Invoke(typeof(GlobalResources), EventArgs.Empty); }
public static AuthenticationResult Failed(AuthenticationError error) => new AuthenticationResult(false, error);
/// <summary> /// Initializes a new instance of the <see cref="SpotifyInvalidRefreshTokenException" /> class. /// </summary> /// <param name="errorCode">The error status code.</param> /// <param name="content">The content.</param> /// <param name="error">The error.</param> public SpotifyInvalidRefreshTokenException(HttpStatusCode errorCode, string content, AuthenticationError error) : base(errorCode, content, error) { }
public CustomAuthException(string message, Exception innerException, AuthenticationError errorCode) : base(message, innerException) { ErrorCode = (int)errorCode; }