Exemplo n.º 1
0
        /// <summary>
        /// Processes logon.
        /// </summary>
        /// <param name="sessionID">Unique session key (created on client side)</param>
        /// <param name="credentials">Logon credentials</param>
        public void Logon(Guid sessionID, Hashtable credentials)
        {
            if (sessionID == Guid.Empty)
            {
                throw new ArgumentException(LanguageResource.ArgumentException_EmptySessionIDIsNotAllowed, "sessionID");
            }

            if (!_host.SessionManager.ExistSession(sessionID))
            {
                // reset current session before authentication is complete
                ServerSession.CurrentSession = null;

                AuthResponseMessage authResponse = _host.Authenticate(new AuthRequestMessage()
                {
                    Credentials = credentials
                });
                if (!authResponse.Success)
                {
                    var exception = authResponse.Exception ?? new SecurityException(authResponse.ErrorMessage);
                    throw exception.PreserveStackTrace();
                }

                var sessionVariableAdapter = new SessionVariableAdapter(_host.SessionManager, sessionID);
                var session = new ServerSession(sessionID, authResponse.AuthenticatedIdentity, sessionVariableAdapter);
                _host.SessionManager.StoreSession(session);
                ServerSession.CurrentSession = session;
                PutClientAddressToCurrentSession();

                _host.OnClientLoggedOn(new LoginEventArgs(LoginEventType.Logon, session.Identity, session.ClientAddress, session.Timestamp));
            }
        }
Exemplo n.º 2
0
        public void AuthResponseMessageTest()
        {
            // try setting value with constructor
            var message = new AuthResponseMessage
            {
                success = true,
                message = "abc"
            };

            Assert.That(message.success, Is.EqualTo(true));
            Assert.That(message.message, Is.EqualTo("abc"));

            // serialize
            var writer = new NetworkWriter(1300);

            writer.Write(message);

            // try deserialize
            var reader = new NetworkReader();

            reader.Reset(writer.ToArraySegment());
            AuthResponseMessage fresh = reader.Read <AuthResponseMessage>();

            Assert.That(fresh.success, Is.EqualTo(true));
            Assert.That(fresh.message, Is.EqualTo("abc"));
            reader.Dispose();
        }
Exemplo n.º 3
0
        public void AuthResponseMessageTest()
        {
            // try setting value with constructor
            AuthResponseMessage message = new AuthResponseMessage
            {
                code    = 123,
                message = "abc"
            };

            Assert.That(message.code, Is.EqualTo(123));
            Assert.That(message.message, Is.EqualTo("abc"));

            // serialize
            NetworkWriter writer = new NetworkWriter();

            message.Serialize(writer);
            byte[] writerData = writer.ToArray();

            // try deserialize
            AuthResponseMessage fresh = new AuthResponseMessage();

            fresh.Deserialize(new NetworkReader(writerData));
            Assert.That(fresh.code, Is.EqualTo(123));
            Assert.That(fresh.message, Is.EqualTo("abc"));
        }
Exemplo n.º 4
0
        public void OnAuthRequestMessage(INetworkConnection conn, AuthRequestMessage msg)
        {
            logger.LogFormat(LogType.Log, "Authentication Request: {0} {1}", msg.AuthUsername, msg.AuthPassword);

            // check the credentials by calling your web server, database table, playfab api, or any method appropriate.
            if (msg.AuthUsername == Username && msg.AuthPassword == Password)
            {
                // create and send msg to client so it knows to proceed
                var authResponseMessage = new AuthResponseMessage
                {
                    Code    = 100,
                    Message = "Success"
                };

                conn.Send(authResponseMessage);

                // Invoke the event to complete a successful authentication
                base.OnServerAuthenticate(conn);
            }
            else
            {
                // create and send msg to client so it knows to disconnect
                var authResponseMessage = new AuthResponseMessage
                {
                    Code    = 200,
                    Message = "Invalid Credentials"
                };

                conn.Send(authResponseMessage);

                // disconnect the client after 1 second so that response message gets delivered
                StartCoroutine(DelayedDisconnect(conn, 1));
            }
        }
Exemplo n.º 5
0
        public void AuthResponseMessageTest()
        {
            // try setting value with constructor
            var message = new AuthResponseMessage
            {
                code    = 123,
                message = "abc"
            };

            Assert.That(message.code, Is.EqualTo(123));
            Assert.That(message.message, Is.EqualTo("abc"));

            // serialize
            var writer = new NetworkWriter();

            writer.Write(message);
            byte[] writerData = writer.ToArray();

            // try deserialize
            var reader = new NetworkReader(writerData);
            AuthResponseMessage fresh = reader.Read <AuthResponseMessage>();

            Assert.That(fresh.code, Is.EqualTo(123));
            Assert.That(fresh.message, Is.EqualTo("abc"));
        }
 private void OnValidateAuthTicketResponse(SteamId steamId, SteamId ownerId, AuthResponse status)
 {
     foreach (KeyValuePair <int, SteamTransport.NetworkPlayer> client in SteamTransport.instance.Server.clients)
     {
         if (client.Value.info.Identity.SteamId == steamId)
         {
             if (logger.LogEnabled())
             {
                 logger.LogFormat(LogType.Log, "Authentication Request: {0} {1}", steamId, status);
             }
             NetworkConnection conn = NetworkServer.connections[client.Key];
             if (status == AuthResponse.OK)
             {
                 AuthResponseMessage authResponseMessage = new AuthResponseMessage();
                 conn.Send(authResponseMessage);
                 // Invoke the event to complete a successful authentication
                 OnServerAuthenticated.Invoke(conn);
                 return;
             }
             else
             {
                 AuthResponseMessage authResponseMessage = new AuthResponseMessage();
                 conn.Send(authResponseMessage);
                 // must set NetworkConnection isAuthenticated = false
                 conn.isAuthenticated = false;
                 // disconnect the client after 1 second so that response message gets delivered
                 StartCoroutine(DelayedDisconnect(conn, 1));
                 return;
             }
         }
     }
 }
        private async Task SendAuthResponse(User user)
        {
            var msg = new AuthResponseMessage {
                name = user?.name, success = user != null
            };

            await SendMessage(msg);
        }
Exemplo n.º 8
0
    /// <summary>
    /// Called on server when the client's AuthRequestMessage arrives
    /// </summary>
    /// <param name="conn">Connection to client.</param>
    /// <param name="msg">The message payload</param>
    public void OnAuthRequestMessage(NetworkConnection conn, AuthRequestMessage msg)
    {
        AuthResponseMessage authResponseMessage = new AuthResponseMessage();

        conn.Send(authResponseMessage);

        // Accept the successful authentication
        ServerAccept(conn);
    }
Exemplo n.º 9
0
        private AuthResponseMessage ResponseStep2(string serverSessionProof, ISrpAccount account)
        {
            var result = new AuthResponseMessage {
                Completed = true, Success = true
            };

            result.AddParameter(SrpProtocolConstants.SRP_SERVER_SESSION_PROOF, serverSessionProof);
            result.AuthenticatedIdentity = AuthRepository.GetIdentity(account);
            return(result);
        }
Exemplo n.º 10
0
        private AuthResponseMessage ResponseStep1(string salt, string serverPublicEphemeral)
        {
            var result = new AuthResponseMessage {
                Completed = false, Success = true
            };

            result.AddParameter(SrpProtocolConstants.SRP_SALT, salt);
            result.AddParameter(SrpProtocolConstants.SRP_SERVER_PUBLIC_EPHEMERAL, serverPublicEphemeral);
            return(result);
        }
Exemplo n.º 11
0
 public void OnClientReceiveLoginResponseMessage(NetworkConnection conn, AuthResponseMessage message)
 {
     if (message.success)
     {
         RpcEnterLobby(message.PlayerID);
     }
     else
     {
         ShowErrors(message.errors);
     }
 }
Exemplo n.º 12
0
 public void OnAuthResponseMessage(NetworkConnection conn, AuthResponseMessage msg)
 {
     if (msg.code == 100)
     {
         ClientAccept(conn);
     }
     else
     {
         Debug.LogError($"Authentication Response: {msg.message}");
         ClientReject(conn);
     }
 }
Exemplo n.º 13
0
 public void OnAuthResponseMessage(NetworkConnection conn, AuthResponseMessage msg)
 {
     if (msg.code == 200)
     {
         OnClientAuthenticated.Invoke(conn);
     }
     else
     {
         conn.isAuthenticated = false;
         conn.Disconnect();
     }
 }
Exemplo n.º 14
0
        /// <summary>
        /// Called on server when the client's AuthRequestMessage arrives
        /// </summary>
        /// <param name="conn">Connection to client.</param>
        /// <param name="msg">The message payload</param>
        public void OnAuthRequestMessage(NetworkConnectionToClient conn, AuthRequestMessage msg)
        {
            Debug.Log($"Authentication Request: {msg.authUsername}");

            if (connectionsPendingDisconnect.Contains(conn))
            {
                return;
            }

            // check the credentials by calling your web server, database table, playfab api, or any method appropriate.
            if (!Player.playerNames.Contains(msg.authUsername))
            {
                // Add the name to the HashSet
                Player.playerNames.Add(msg.authUsername);

                // Store username in authenticationData
                // This will be read in Player.OnStartServer
                // to set the playerName SyncVar.
                conn.authenticationData = msg.authUsername;

                // create and send msg to client so it knows to proceed
                AuthResponseMessage authResponseMessage = new AuthResponseMessage
                {
                    code    = 100,
                    message = "Success"
                };

                conn.Send(authResponseMessage);

                // Accept the successful authentication
                ServerAccept(conn);
            }
            else
            {
                connectionsPendingDisconnect.Add(conn);

                // create and send msg to client so it knows to disconnect
                AuthResponseMessage authResponseMessage = new AuthResponseMessage
                {
                    code    = 200,
                    message = "Username already in use...try again"
                };

                conn.Send(authResponseMessage);

                // must set NetworkConnection isAuthenticated = false
                conn.isAuthenticated = false;

                // disconnect the client after 1 second so that response message gets delivered
                StartCoroutine(DelayedDisconnect(conn, 1f));
            }
        }
Exemplo n.º 15
0
    private void AuthReceivedFromServer(NetworkConnection connection, AuthResponseMessage msg)
    {
        if (!msg.success)
        {
            Debug.Log($"Authentication failure: {msg.errorMessage}");
            authFailed.Invoke(msg.errorMessage);
            NetworkManager.singleton.StopClient();
            return;
        }

        Debug.Log($"Authentication succeeded");
        base.OnClientAuthenticated.Invoke(connection);
    }
Exemplo n.º 16
0
    public IEnumerator DelayedDisconnect(NetworkConnection conn, string message)
    {
        // create and send msg to client so it knows to disconnect
        AuthResponseMessage authResponseMessage = new AuthResponseMessage {
            code    = 401,
            message = message
        };

        conn.Send(authResponseMessage);
        conn.isAuthenticated = false;

        yield return(new WaitForSeconds(1f));

        conn.Disconnect();
    }
Exemplo n.º 17
0
        public void OnAuthResponseMessage2(NetworkConnection conn, AuthResponseMessage msg)
        {
            if (msg.code == 100)
            {
                if (logger.LogEnabled())
                {
                    logger.LogFormat(LogType.Log, "Authentication Response: {0}", msg.message);
                }
                helpText.text = "Logging in!";

                if (File.Exists(charStreamPath + msg.username + ".json"))
                {
                    Character character;
                    using (StreamReader stream = new StreamReader(charStreamPath + msg.username + ".json"))
                    {
                        string json = stream.ReadToEnd();
                        character = JsonUtility.FromJson <Character>(json);
                    }

                    List <string> m_DropOptions = new List <string> {
                        character.name
                    };


                    Debug.Log(character.name);
                    string n = character.name;
                    loginUI.GetComponent <UILogin>().characterSelectUI.SetActive(true);
                    loginUI.GetComponent <UILogin>().characterList.AddOptions(m_DropOptions);
                }
                else
                {
                    Debug.Log("No Character for account");
                    characterUI.SetActive(true);
                }

                Debug.Log("Success Login");
            }
            else
            {
                // logger.LogFormat(LogType.Error, "Authentication Response: {0}", msg.message);
                helpText.text = "Wrong Password!";
                // Set this on the client for local reference
                conn.isAuthenticated = false;

                // disconnect the client
                conn.Disconnect();
            }
        }
Exemplo n.º 18
0
 private void OnAuthResponseMessage(INetworkPlayer player, AuthResponseMessage msg)
 {
     if (msg.success)
     {
         if (logger.LogEnabled())
         {
             logger.LogFormat(LogType.Log, "Authentication Success: {0}", msg.message);
         }
         ClientAccept(player);
     }
     else
     {
         logger.LogFormat(LogType.Error, "Authentication Fail: {0}", msg.message);
         ClientReject(player);
     }
 }
Exemplo n.º 19
0
        /// <summary>
        /// Called on client when the server's AuthResponseMessage arrives
        /// </summary>
        /// <param name="msg">The message payload</param>
        public void OnAuthResponseMessage(AuthResponseMessage msg)
        {
            if (msg.code == 100)
            {
                // Debug.LogFormat(LogType.Log, "Authentication Response: {0}", msg.message);

                // Authentication has been accepted
                ClientAccept();
            }
            else
            {
                Debug.LogError($"Authentication Response: {msg.message}");

                // Authentication has been rejected
                ClientReject();
            }
        }
Exemplo n.º 20
0
        public void OnAuthResponseMessage(INetworkConnection conn, AuthResponseMessage msg)
        {
            if (msg.Code == 100)
            {
                logger.LogFormat(LogType.Log, "Authentication Response: {0}", msg.Message);

                // Invoke the event to complete a successful authentication
                base.OnClientAuthenticate(conn);
            }
            else
            {
                logger.LogFormat(LogType.Error, "Authentication Response: {0}", msg.Message);

                // disconnect the client
                conn.Disconnect();
            }
        }
Exemplo n.º 21
0
    private void RequestAuthForClient(NetworkConnection connection, AuthRequestMessage msg)
    {
        PruneDisconnected();

        AuthResponseMessage errorResponse = null;

        if (msg.nickname.Length == 0)
        {
            errorResponse = new AuthResponseMessage {
                success = false, errorMessage = $"Nickname cannot be empty"
            };
        }
        else if (nicknames.ContainsValue(msg.nickname))
        {
            errorResponse = new AuthResponseMessage {
                success = false, errorMessage = $"Nickname \"{msg.nickname}\" is already taken on this server"
            };
        }
        else if (nicknames.ContainsKey(connection.connectionId))
        {
            errorResponse = new AuthResponseMessage {
                success = false, errorMessage = $"Client already connected!"
            };
        }

        if (errorResponse != null)
        {
            Debug.Log($"Rejecting attempted auth for \"{msg.nickname}\": {errorResponse.errorMessage}");
            connection.Send(errorResponse);
            return;
        }

        var authData = new MercAuthenticationData {
            nickname = msg.nickname
        };

        Debug.Log($"\"{authData.nickname}\" connected (running version {msg.clientVersion})");
        nicknames.Add(connection.connectionId, authData.nickname);

        connection.authenticationData = authData;
        connection.Send(new AuthResponseMessage {
            success = true
        });
        base.OnServerAuthenticated.Invoke(connection);
    }
Exemplo n.º 22
0
 // -------------------------------------------------------------------------------
 public void OnAuthResponseMessage(NetworkConnection conn, AuthResponseMessage msg)
 {
     if (msg.code == 100)
     {
         base.OnClientAuthenticated.Invoke(conn);
         ClientScene.Ready(conn);
         conn.Send(new LoginMessage {
             authUsername = username, authPassword = GenerateHash()
         });
         //UIModalConfirm.singleton.Show(msg.message);
     }
     else
     {
         conn.isAuthenticated = false;
         conn.Disconnect();
         UIModalConfirm.singleton.Show(msg.message);
     }
 }
        /// <summary>
        /// Called on server when the client's AuthRequestMessage arrives
        /// </summary>
        /// <param name="conn">Connection to client.</param>
        /// <param name="msg">The message payload</param>
        public void OnAuthRequestMessage(NetworkConnection conn, AuthRequestMessage msg)
        {
            // Debug.LogFormat(LogType.Log, "Authentication Request: {0} {1}", msg.authUsername, msg.authPassword);

            if (connectionsPendingDisconnect.Contains(conn))
            {
                return;
            }

            // check the credentials by calling your web server, database table, playfab api, or any method appropriate.
            if (msg.authUsername == serverUsername && msg.authPassword == serverPassword)
            {
                // create and send msg to client so it knows to proceed
                AuthResponseMessage authResponseMessage = new AuthResponseMessage
                {
                    code    = 100,
                    message = "Success"
                };

                conn.Send(authResponseMessage);

                // Accept the successful authentication
                ServerAccept(conn);
            }
            else
            {
                connectionsPendingDisconnect.Add(conn);

                // create and send msg to client so it knows to disconnect
                AuthResponseMessage authResponseMessage = new AuthResponseMessage
                {
                    code    = 200,
                    message = "Invalid Credentials"
                };

                conn.Send(authResponseMessage);

                // must set NetworkConnection isAuthenticated = false
                conn.isAuthenticated = false;

                // disconnect the client after 1 second so that response message gets delivered
                StartCoroutine(DelayedDisconnect(conn, 1));
            }
        }
        public void OnAuthResponseMessage(NetworkConnection conn, AuthResponseMessage msg)
        {
            AuthResponse authResponse = (AuthResponse)msg.status;

            if (logger.LogEnabled())
            {
                logger.LogFormat(LogType.Log, "Authentication Response: {0}", authResponse.ToString());
            }
            if (authResponse == AuthResponse.OK)
            {
                // Invoke the event to complete a successful authentication
                OnClientAuthenticated.Invoke(conn);
            }
            else
            {
                conn.isAuthenticated = false;
                conn.Disconnect();
            }
        }
Exemplo n.º 25
0
        public void OnAuthResponseMessage(NetworkConnection conn, AuthResponseMessage msg)
        {
            if (msg.code == 100)
            {
                Debug.LogFormat("Authentication Response: {0}", msg.message);

                // Invoke the event to complete a successful authentication
                base.OnClientAuthenticated.Invoke(conn);
            }
            else
            {
                Debug.LogErrorFormat("Authentication Response: {0}", msg.message);

                // Set this on the client for local reference
                conn.isAuthenticated = false;

                // disconnect the client
                conn.Disconnect();
            }
        }
Exemplo n.º 26
0
        /// <summary>
        /// Called on client when the server's AuthResponseMessage arrives
        /// </summary>
        /// <param name="conn">Connection to client.</param>
        /// <param name="msg">The message payload</param>
        public void OnAuthResponseMessage(NetworkConnection conn, AuthResponseMessage msg)
        {
            if (msg.code == 100)
            {
                if (logger.LogEnabled())
                {
                    logger.LogFormat(LogType.Info, "Authentication Response: {0}", msg.message);
                }

                // Authentication has been accepted
                ClientAccept(conn);
            }
            else
            {
                logger.LogFormat(LogType.Error, "Authentication Response: {0}", msg.message);

                // Authentication has been rejected
                ClientReject(conn);
            }
        }
Exemplo n.º 27
0
        // -------------------------------------------------------------------------------
        public void OnAuthRequestMessage(NetworkConnection conn, AuthRequestMessage msg)
        {
            int nErrors = 0;

            AuthResponseMessage authResponseMessage = new AuthResponseMessage
            {
                code    = 100,
                message = "Success"
            };

            if ((msg.authAction == "REGISTER" || msg.authAction == "BOTH") && Database.singleton.TryRegister(msg.authUsername, msg.authPassword))
            {
                manager.CreatePlayer(msg.authUsername);
            }
            else if (msg.authAction == "REGISTER")
            {
                nErrors++;
            }

            if ((msg.authAction == "LOGIN" || msg.authAction == "BOTH") && !Database.singleton.TryLogin(msg.authUsername, msg.authPassword))
            {
                nErrors++;
            }

            if (nErrors > 0)
            {
                authResponseMessage.code    = 200;
                authResponseMessage.message = "Invalid Credentials";
            }
            else
            {
                base.OnServerAuthenticated.Invoke(conn);
                conn.Send(authResponseMessage);
            }

            if (nErrors > 0)
            {
                conn.isAuthenticated = false;
                Invoke(nameof(conn.Disconnect), 1);
            }
        }
Exemplo n.º 28
0
        /// <summary>
        /// Called on client when the server's AuthResponseMessage arrives
        /// </summary>
        /// <param name="msg">The message payload</param>
        public void OnAuthResponseMessage(AuthResponseMessage msg)
        {
            if (msg.code == 100)
            {
                Debug.Log($"Authentication Response: {msg.message}");

                // Authentication has been accepted
                ClientAccept();
            }
            else
            {
                Debug.LogError($"Authentication Response: {msg.message}");

                // Authentication has been rejected
                // StopHost works for both host client and remote clients
                NetworkManager.singleton.StopHost();

                // Do this AFTER StopHost so it doesn't get cleared / hidden by OnClientDisconnect
                LoginUI.instance.errorText.text = msg.message;
                LoginUI.instance.errorText.gameObject.SetActive(true);
            }
        }
        public void OnAuthResponseMessage(NetworkConnection conn, AuthResponseMessage msg)
        {
            if (msg.code == 100)
            {
                if (logger.LogEnabled())
                {
                    logger.LogFormat(LogType.Log, "Authentication Response: {0}", msg.message);
                }
                clientStatus = "Ticket accepted";
                // Invoke the event to complete a successful authentication
                OnClientAuthenticated.Invoke(conn);
            }
            else
            {
                logger.LogFormat(LogType.Error, "Authentication Response: {0}", msg.message);
                clientStatus = String.Format("Ticket rejected ({0})", msg.message);

                // Set this on the client for local reference
                conn.isAuthenticated = false;

                // disconnect the client
                conn.Disconnect();

                // debug/test...
                if (!String.IsNullOrEmpty(getServerKey()))
                {
                    TimedTicket t = new TimedTicket();
                    try {
                        t.Parse(ticketString);
                        t.Sign(getServerKey());
                        string ts = t.ToString();
                        logger.LogFormat(LogType.Error, "Self-sign ticket: {0}", ts);
                    } catch (FormatException e) {
                        logger.LogFormat(LogType.Error, "problem making self-sign ticket: {0}", e);
                    }
                }
            }
        }
Exemplo n.º 30
0
    public async void OnAuthRequestMessage(NetworkConnection conn, AuthRequestMessage msg)
    {
        bool isValid = await loginService.Validate(msg.accessToken);

        if (!isValid)
        {
            StartCoroutine(DelayedDisconnect(conn, "Invalid access token."));
            return;
        }

        Jwt jwt = new Jwt(msg.accessToken);

        string[] allowedUserIds = GameState.singleton.gameServerModel.allowedUserIds;
        if (allowedUserIds.Length > 0 && !allowedUserIds.Contains(jwt.payload.user._id))
        {
            StartCoroutine(DelayedDisconnect(conn, "User not allowed."));
            return;
        }
        Debug.Log("User is allowed.");

        // Set authenticationData for other scripts to use.
        GroupModel groupModel = await GetGroupModel(msg.groupId, jwt.payload.user._id);

        conn.authenticationData = new AuthenticationData {
            groupModel = groupModel,
            userModel  = jwt.payload.user
        };

        // Create and send msg to client so it knows to proceed.
        AuthResponseMessage authResponseMessage = new AuthResponseMessage {
            code    = 200,
            message = "Success"
        };

        conn.Send(authResponseMessage);

        OnServerAuthenticated.Invoke(conn);
    }