Example #1
0
        private void ValidateProxyTicket(Uri validateUrl)
        {
            try
            {
                string         xml;
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(validateUrl);
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                    {
                        xml = reader.ReadToEnd();
                        ServerResponseField.Text = xml.Replace("\n\n\n", "\n").Replace("\n\n", "\n").Replace("\n", Environment.NewLine).Replace("\t", "  ");

                        StringReader sr = new StringReader(xml);

                        XmlSerializer   serializer      = new XmlSerializer(typeof(ServiceResponse));
                        ServiceResponse serviceResponse = serializer.Deserialize(sr) as ServiceResponse;

                        if (serviceResponse != null)
                        {
                            if (serviceResponse.IsAuthenticationSuccess)
                            {
                                AuthenticationSuccess successResponse = (AuthenticationSuccess)serviceResponse.Item;
                                StatusField.Text           = "SUCCESS";
                                StatusField.ForeColor      = Color.Green;
                                StatusColorField.BackColor = Color.Green;
                                UsernameField.Text         = successResponse.User;
                                ProxiesField.DataSource    = successResponse.Proxies;
                            }
                            else if (serviceResponse.IsAuthenticationFailure)
                            {
                                AuthenticationFailure failureResponse = (AuthenticationFailure)serviceResponse.Item;
                                StatusField.Text           = "FAILURE";
                                StatusField.ForeColor      = Color.Green;
                                StatusColorField.BackColor = Color.Red;
                                UsernameLabel.Text         = "Code " + failureResponse.Code;
                                MessageLabel.Text          = failureResponse.Message;
                            }
                            else
                            {
                                StatusField.Text             = "UNEXPECTED RESPONSE";
                                StatusColorField.BackColor   = Color.Yellow;
                                StatusExceptionField.Visible = true;
                            }
                        }
                    }
                }
            }
            catch (Exception exc)
            {
                StatusField.Text             = "EXCEPTION";
                ServerResponseField.Text     = exc.ToString();
                StatusColorField.BackColor   = Color.Yellow;
                StatusExceptionField.Visible = true;
            }
        }
Example #2
0
        public void RecordAuthenticationFailure(Guid _userGuid)
        {
            AuthenticationFailureDAO dao = new AuthenticationFailureDAO(MongoDB);

            AuthenticationFailure failure = new AuthenticationFailure
            {
                Guid         = Guid.NewGuid(),
                ParentGuid   = _userGuid,
                FailureTicks = DateTime.UtcNow.Ticks
            };

            dao.Persist(failure);
        }
Example #3
0
        //TODO: 8-9-2010 -- prevent against multiple hooks here

        #region IFailureHandler Members
        /// <summary>	Executes the authentication failure action. </summary>
        /// <remarks>	ebrown, 1/3/2011. </remarks>
        /// <param name="context">		    The incoming HttpContextBase. </param>
        /// <param name="inspectorResults">	The set of failed inspector results. </param>
        /// <returns>	An IPrincipal instance / ShouldTerminateRequest value as returned by the failure event handler. </returns>
        public override FailureHandlerAction OnAuthenticationFailure(
            HttpContextBase context,
            Dictionary <IAuthenticator,
                        AuthenticationResult> inspectorResults)
        {
            var eventArgs = new SimpleFailureEventArgs(Configuration, context, inspectorResults);

            AuthenticationFailure.SafeInvoke(this, eventArgs);

            return(new FailureHandlerAction()
            {
                User = eventArgs.IPrincipal, ShouldTerminateRequest = eventArgs.ShouldTerminateRequest
            });
        }
Example #4
0
        public void AddFailureToModelState(
            AuthenticationFailure <UsernamePasswordAuthenticateFailureReason> failure,
            ModelStateDictionary modelState)
        {
            foreach (var reason in failure.FailureReasons)
            {
                switch (reason)
                {
                case UsernamePasswordAuthenticateFailureReason.UsernameIsEmpty:
                    modelState.AddModelError <LoginDisplayModel>(m => m.Form.Username, "The user name is empty.");
                    break;

                case UsernamePasswordAuthenticateFailureReason.PasswordIsEmpty:
                    modelState.AddModelError <LoginDisplayModel>(m => m.Form.Password, "The password is empty.");
                    break;

                case UsernamePasswordAuthenticateFailureReason.InvalidCredentials:
                    modelState.AddModelError <LoginDisplayModel>(m => m.Form.Password, "The specified credentials are invalid.");
                    break;
                }
            }
        }
Example #5
0
        /// <summary>
        /// Try to parse broker exception from the message
        /// </summary>
        /// <param name="messageFault">indicating the message fault</param>
        /// <param name="action">indicating the action</param>
        /// <param name="brokerException">output the broker exception</param>
        /// <returns>returns a value indicating whether successfully parsed out broker exception</returns>
        private static bool TryParseBrokerException(MessageFault messageFault, string action, out Exception brokerException)
        {
            switch (action)
            {
            case AuthenticationFailure.Action:
                AuthenticationFailure af = messageFault.GetDetail <AuthenticationFailure>();
                brokerException = new AuthenticationException(String.Format(SR.Broker_AuthenticationFailure, af.UserName));
                return(true);

            case RetryOperationError.Action:
                RetryOperationError rle = messageFault.GetDetail <RetryOperationError>();
                brokerException = new RetryOperationException(String.Format(SR.Broker_RetryLimitExceeded, rle.RetryCount, rle.Reason), rle.Reason);
                return(true);

            case SessionFault.Action:
                SessionFault fault = messageFault.GetDetail <SessionFault>();
                brokerException = Utility.TranslateFaultException(new FaultException <SessionFault>(fault, messageFault.Reason));
                return(true);

            default:
                brokerException = null;
                return(false);
            }
        }
Example #6
0
 public FailedAuthentication(AuthenticationFailure failure, string reason = "")
 {
     Failure = failure;
     Reason  = reason;
 }
Example #7
0
 internal void HandleAuthenticationFailure(object sender, EventArgs args)
 {
     WrappedEventHandler(() => AuthenticationFailure?.Invoke(sender, args), "AuthenticationFailure", sender);
 }
 internal void HandleAuthenticationFailure(object sender, EventArgs args)
 {
     AuthenticationFailure?.Invoke(sender, args);
 }
Example #9
0
        /// <summary>
        /// Parses the response from the server into a CAS Assertion and includes this in
        /// a CASPrincipal.
        /// <remarks>
        /// Parsing of a &lt;cas:attributes&gt; element is <b>not</b> supported.  The official
        /// CAS 2.0 protocol does include this feature.  If attributes are needed,
        /// SAML must be used.
        /// </remarks>
        /// </summary>
        /// <param name="response">the response from the server, in any format.</param>
        /// <param name="ticket">The ticket used to generate the validation response</param>
        /// <returns>
        /// a Principal backed by a CAS Assertion, if one could be created from the response.
        /// </returns>
        /// <exception cref="TicketValidationException">
        /// Thrown if creation of the Assertion fails.
        /// </exception>
        protected override ICasPrincipal ParseResponseFromServer(string response, string ticket)
        {
            if (String.IsNullOrEmpty(response))
            {
                throw new TicketValidationException("CAS Server response was empty.");
            }

            ServiceResponse serviceResponse;

            try
            {
                serviceResponse = ServiceResponse.ParseResponse(response);
            }
            catch (InvalidOperationException)
            {
                throw new TicketValidationException("CAS Server response does not conform to CAS 2.0 schema");
            }

            if (serviceResponse.IsAuthenticationSuccess)
            {
                AuthenticationSuccess authSuccessResponse = (AuthenticationSuccess)serviceResponse.Item;

                if (String.IsNullOrEmpty(authSuccessResponse.User))
                {
                    throw new TicketValidationException(string.Format("CAS Server response parse failure: missing 'cas:user' element."));
                }

                string proxyGrantingTicketIou = authSuccessResponse.ProxyGrantingTicket;

                if (CasAuthentication.ProxyTicketManager != null && !string.IsNullOrEmpty(proxyGrantingTicketIou))
                {
                    string proxyGrantingTicket = CasAuthentication.ProxyTicketManager.GetProxyGrantingTicket(proxyGrantingTicketIou);
                    if (proxyGrantingTicket != null)
                    {
                        CasAuthentication.ProxyTicketManager.InsertProxyGrantingTicketMapping(proxyGrantingTicketIou, proxyGrantingTicket);
                    }
                }

                if (authSuccessResponse.Proxies != null && authSuccessResponse.Proxies.Length > 0)
                {
                    return(new CasPrincipal(new Assertion(authSuccessResponse.User), proxyGrantingTicketIou, authSuccessResponse.Proxies));
                }
                else
                {
                    return(new CasPrincipal(new Assertion(authSuccessResponse.User), proxyGrantingTicketIou));
                }
            }

            if (serviceResponse.IsAuthenticationFailure)
            {
                try
                {
                    AuthenticationFailure authFailureResponse = (AuthenticationFailure)serviceResponse.Item;
                    throw new TicketValidationException(authFailureResponse.Message, authFailureResponse.Code);
                }
                catch
                {
                    throw new TicketValidationException("CAS ticket could not be validated.");
                }
            }

            if (serviceResponse.IsProxySuccess)
            {
                throw new TicketValidationException("Unexpected service validate response: ProxySuccess");
            }

            if (serviceResponse.IsProxyFailure)
            {
                throw new TicketValidationException("Unexpected service validate response: ProxyFailure");
            }

            throw new TicketValidationException("Failed to validate CAS ticket.");
        }
Example #10
0
 internal void HandleAuthenticationFailure(object sender, EventArgs args)
 {
     CatchAndReport(() => AuthenticationFailure?.Invoke(sender, args), "AuthenticationFailure", sender);
 }
Example #11
0
 public FailedAuthentication(AuthenticationFailure failure)
 {
     this.Failure = failure;
 }
Example #12
0
 public FailedAuthentication(AuthenticationFailure failure, string reason)
 {
     this.Failure = failure;
     this.Reason  = reason;
 }
        private async Task DataReceiver()
        {
            while (true)
            {
                bool readLocked = false;

                try
                {
                    _Token.ThrowIfCancellationRequested();

                    if (_Client == null ||
                        !_Client.Connected ||
                        _Token.IsCancellationRequested)
                    {
                        Logger?.Invoke("[WatsonTcpClient] Disconnect detected");
                        break;
                    }

                    WatsonMessage msg = null;
                    readLocked = await _ReadLock.WaitAsync(1);

                    bool buildSuccess = false;

                    if (_SslStream != null)
                    {
                        msg = new WatsonMessage(_SslStream, Debug);
                    }
                    else
                    {
                        msg = new WatsonMessage(_TcpStream, Debug);
                    }

                    if (_MessageReceived != null &&
                        _MessageReceived.GetInvocationList().Length > 0)
                    {
                        buildSuccess = await msg.Build();
                    }
                    else if (_StreamReceived != null &&
                             _StreamReceived.GetInvocationList().Length > 0)
                    {
                        buildSuccess = await msg.BuildStream();
                    }
                    else
                    {
                        break;
                    }

                    if (!buildSuccess)
                    {
                        Logger?.Invoke("[WatsonTcpClient] Message build failed due to disconnect");
                        break;
                    }

                    if (msg == null)
                    {
                        await Task.Delay(30);

                        continue;
                    }

                    if (msg.Status == MessageStatus.Removed)
                    {
                        Logger?.Invoke("[WatsonTcpClient] Disconnect due to server-side removal");
                        break;
                    }
                    else if (msg.Status == MessageStatus.Disconnecting)
                    {
                        Logger?.Invoke("[WatsonTcpClient] Disconnect due to server shutdown");
                        break;
                    }
                    else if (msg.Status == MessageStatus.AuthSuccess)
                    {
                        Logger?.Invoke("[WatsonTcpClient] Authentication successful");
                        AuthenticationSucceeded?.Invoke(this, EventArgs.Empty);
                        continue;
                    }
                    else if (msg.Status == MessageStatus.AuthFailure)
                    {
                        Logger?.Invoke("[WatsonTcpClient] Authentication failed");
                        AuthenticationFailure?.Invoke(this, EventArgs.Empty);
                        continue;
                    }

                    if (msg.Status == MessageStatus.AuthRequired)
                    {
                        Logger?.Invoke("[WatsonTcpClient] Authentication required by server; please authenticate using pre-shared key");
                        if (AuthenticationRequested != null)
                        {
                            string psk = AuthenticationRequested();
                            if (!String.IsNullOrEmpty(psk))
                            {
                                Authenticate(psk);
                            }
                        }
                        continue;
                    }

                    if (_MessageReceived != null &&
                        _MessageReceived.GetInvocationList().Length > 0)
                    {
                        MessageReceivedFromServerEventArgs args = new MessageReceivedFromServerEventArgs(msg.Metadata, msg.Data);
                        _MessageReceived?.Invoke(this, args);
                    }
                    else if (_StreamReceived != null &&
                             _StreamReceived.GetInvocationList().Length > 0)
                    {
                        StreamReceivedFromServerEventArgs args = new StreamReceivedFromServerEventArgs(msg.Metadata, msg.ContentLength, msg.DataStream);
                        _StreamReceived?.Invoke(this, args);
                    }
                    else
                    {
                        break;
                    }

                    _Stats.ReceivedMessages = _Stats.ReceivedMessages + 1;
                    _Stats.ReceivedBytes   += msg.ContentLength;
                }
                catch (Exception e)
                {
                    Logger?.Invoke(
                        "[WatsonTcpClient] Data receiver exception: " +
                        Environment.NewLine +
                        e.ToString() +
                        Environment.NewLine);
                    break;
                }
                finally
                {
                    if (readLocked)
                    {
                        _ReadLock.Release();
                    }
                }
            }

            Logger?.Invoke("[WatsonTcpClient] Data receiver terminated");
            Connected = false;
            ServerDisconnected?.Invoke(this, EventArgs.Empty);
            Dispose();
        }