示例#1
0
        private void BeginReceiveCallback(IAsyncResult results)
        {
            var state = (AuthenticationState)results.AsyncState;

            // Timeout, socket has been closed.
            if (state.client.Client == null)
            {
                return;
            }

            var packet = (AuthenticationPacket)PacketSerializer.Deserialize(state.buffer)[0];
            var auth   = state.auth;

            if (packet.version == auth.version &&
                packet.time == auth.time &&
                !string.IsNullOrEmpty(packet.response) &&
                Guid.Parse(packet.guid) == state.guid)
            {
                AuthenticationSuccess?.Invoke(state.client, packet);
            }
            else
            {
                AuthenticationFailed?.Invoke(state.client);
            }
        }
示例#2
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;
            }
        }
示例#3
0
        public void Authenticate(string username, string password)
        {
            UserAccount _userAccount;
            var         authResult = TryAuthenticate(username, password, out _userAccount);

            switch (authResult)
            {
            case AuthenticationResult.Success:
            {
                connectToAccount(_userAccount);
                AuthenticationSuccess.Raise(CurrentUserAccount);
                break;
            }

            default:
            {
                AuthenticationFailed.Raise(authResult);
                break;
            }
            }
        }
        /// <summary>
        /// Processes an incoming command frame from the connection.
        /// Captures the call if it is a Rpc command.
        /// </summary>
        /// <param name="frame">Command frame to process.</param>
        protected override void ProcessCommand(MqFrame frame)
        {
            var commandType = (MqCommandType)frame.ReadByte(0);

            // If this is a base MqCommand, pass this directly on to the base command handler.
            if (commandType != MqCommandType.RpcCommand)
            {
                base.ProcessCommand(frame);
                return;
            }

            try
            {
                var rpcCommandType = (RpcCommandType)frame.ReadByte(1);

                if (rpcCommandType == RpcCommandType.WelcomeMessage)
                {
                    // RpcCommand:byte; RpcCommandType:byte; RpcServerInfoDataContract:byte[];

                    // Ensure that this command is running on the client.
                    if (BaseSocket.Mode != SocketMode.Client)
                    {
                        Close(SocketCloseReason.ProtocolError);
                        return;
                    }

                    var serializer = SerializationCache.Get(new MqMessage(frame));

                    // Forward the reader two bytes to the data.
                    serializer.MessageReader.ReadBytes(2);

                    serializer.PrepareDeserializeReader();

                    // Try to read the information from the server about the server.
                    Client.ServerInfo =
                        serializer.DeserializeFromReader(typeof(RpcServerInfoDataContract)) as RpcServerInfoDataContract;

                    if (Client.ServerInfo == null)
                    {
                        Close(SocketCloseReason.ProtocolError);
                        return;
                    }

                    // Check to see if the server requires authentication.  If so, send a auth check.
                    if (Client.ServerInfo.RequireAuthentication)
                    {
                        var authArgs = new RpcAuthenticateEventArgs <TSession, TConfig>((TSession)this);

                        // Start the authentication event to get the auth data.
                        Authenticate?.Invoke(this, authArgs);

                        serializer.MessageWriter.Write((byte)MqCommandType.RpcCommand);
                        serializer.MessageWriter.Write((byte)RpcCommandType.AuthenticationRequest);

                        if (authArgs.AuthData == null)
                        {
                            authArgs.AuthData = new byte[] { 0 };
                        }


                        serializer.MessageWriter.Write(authArgs.AuthData, 0, authArgs.AuthData.Length);

                        var authMessage = serializer.MessageWriter.ToMessage(true);
                        authMessage[0].FrameType = MqFrameType.Command;

                        _authTimeout = new Task(async() =>
                        {
                            try
                            {
                                await Task.Delay(Config.ConnectionTimeout, _authTimeoutCancel.Token);
                            }
                            catch
                            {
                                return;
                            }

                            if (!_authTimeoutCancel.IsCancellationRequested)
                            {
                                Close(SocketCloseReason.TimeOut);
                            }
                        });

                        // RpcCommand:byte; RpcCommandType:byte; AuthData:byte[];
                        Send(authMessage);

                        _authTimeout.Start();
                    }
                    else
                    {
                        // If no authentication is required, set this client to authenticated.
                        Authenticated = true;

                        // Alert the server that this session is ready for usage.
                        Task.Run(
                            () => { Ready?.Invoke(this, new SessionEventArgs <TSession, TConfig>((TSession)this)); });
                    }

                    SerializationCache.Put(serializer);
                }
                else if (rpcCommandType == RpcCommandType.AuthenticationRequest)
                {
                    // RpcCommand:byte; RpcCommandType:byte; AuthData:byte[];

                    // If this is not run on the server, quit.
                    if (BaseSocket.Mode != SocketMode.Server)
                    {
                        Close(SocketCloseReason.ProtocolError);
                        return;
                    }

                    // Ensure that the server requires authentication.
                    if (Server.Config.RequireAuthentication == false)
                    {
                        Close(SocketCloseReason.ProtocolError);
                        return;
                    }

                    byte[] authBytes = new byte[frame.DataLength - 2];
                    frame.Read(2, authBytes, 0, authBytes.Length);

                    var authArgs = new RpcAuthenticateEventArgs <TSession, TConfig>((TSession)this)
                    {
                        AuthData = authBytes
                    };


                    Authenticate?.Invoke(this, authArgs);

                    Authenticated = authArgs.Authenticated;

                    if (Authenticated == false)
                    {
                        Close(SocketCloseReason.AuthenticationFailure);
                    }
                    else
                    {
                        var authFrame = CreateFrame(new byte[authArgs.AuthData.Length + 2], MqFrameType.Command);
                        authFrame.Write(0, (byte)MqCommandType.RpcCommand);
                        authFrame.Write(1, (byte)RpcCommandType.AuthenticationResult);

                        // State of the authentication
                        authFrame.Write(2, Authenticated);

                        // RpcCommand:byte; RpcCommandType:byte; AuthResult:bool;
                        Send(authFrame);

                        // Alert the server that this session is ready for usage.
                        Task.Run(
                            () => { Ready?.Invoke(this, new SessionEventArgs <TSession, TConfig>((TSession)this)); });
                    }
                }
                else if (rpcCommandType == RpcCommandType.AuthenticationResult)
                {
                    // RpcCommand:byte; RpcCommandType:byte; AuthResult:bool;

                    // Cancel the timeout request.
                    _authTimeoutCancel.Cancel();

                    // Ensure that this command is running on the client.
                    if (BaseSocket.Mode != SocketMode.Client)
                    {
                        Close(SocketCloseReason.ProtocolError);
                        return;
                    }

                    if (Client.Config.RequireAuthentication == false)
                    {
                        Close(SocketCloseReason.ProtocolError);
                        return;
                    }

                    Authenticated = true;

                    var authArgs = new RpcAuthenticateEventArgs <TSession, TConfig>((TSession)this)
                    {
                        Authenticated = frame.ReadBoolean(2)
                    };

                    // Alert the client that the sesion has been authenticated.
                    AuthenticationSuccess?.Invoke(this, authArgs);

                    // Alert the client that this session is ready for usage.
                    Task.Run(() => { Ready?.Invoke(this, new SessionEventArgs <TSession, TConfig>((TSession)this)); });
                }
                else
                {
                    Close(SocketCloseReason.ProtocolError);
                }
            }
            catch (Exception)
            {
                Close(SocketCloseReason.ProtocolError);
            }
        }
示例#5
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.");
        }