Example #1
0
            public AuthResponseMessage Authenticate(AuthRequestMessage authRequest)
            {
                if (authRequest.Credentials == null)
                {
                    return(Error("No credentials specified"));
                }

                var stepNumber = 0;

                if (authRequest.Credentials.ContainsKey("#"))
                {
                    stepNumber = (int)(authRequest.Credentials["#"]);
                }

                var payload = string.Empty;

                if (authRequest.Credentials.ContainsKey("@"))
                {
                    payload = (string)(authRequest.Credentials["@"]);
                }

                switch (stepNumber)
                {
                case 0: return(payload == "Hello" ? Ok(false, "World") : Error("Failure on step 0"));

                case 1: return(payload == "Icanhaz" ? Ok(true, "Cheezburger") : Error("Failure on step 1"));
                }

                return(Error("Bad authentication"));
            }
Example #2
0
        public void AuthRequestMessageTest()
        {
            // try setting value with constructor
            AuthRequestMessage message = new AuthRequestMessage
            {
                authUsername = "******",
                authPassword = "******"
            };

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

            // serialize
            NetworkWriter writer = new NetworkWriter();

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

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

            fresh.Deserialize(new NetworkReader(writerData));
            Assert.That(fresh.authUsername, Is.EqualTo("abc"));
            Assert.That(fresh.authPassword, Is.EqualTo("123"));
        }
 public void OnAuthRequestMessage(NetworkConnection conn, AuthRequestMessage msg)
 {
     if (logger.LogEnabled())
     {
         logger.LogFormat(LogType.Log, "Begin Authentication Session: {0}", msg.steamId);
     }
     SteamServer.BeginAuthSession(msg.ticket, msg.steamId);
 }
Example #4
0
    public override void OnClientAuthenticate(NetworkConnection connection)
    {
        Debug.Log($"Sending authentication request as \"{nickname}\"");
        AuthRequestMessage authRequestMessage = new AuthRequestMessage {
            clientVersion = Application.version, nickname = nickname
        };

        NetworkClient.Send(authRequestMessage);
    }
Example #5
0
        /// <summary>
        /// Called on client from OnClientConnectInternal when a client needs to authenticate
        /// </summary>
        public override void OnClientAuthenticate()
        {
            AuthRequestMessage authRequestMessage = new AuthRequestMessage
            {
                authUsername = playerName,
            };

            NetworkClient.connection.Send(authRequestMessage);
        }
Example #6
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);
    }
Example #7
0
    public override void OnClientAuthenticate(NetworkConnection conn)
    {
        AuthRequestMessage authRequestMessage = new AuthRequestMessage
        {
            authUsername = playerData.PlayerLogin
        };

        conn.Send(authRequestMessage);
    }
        /// <summary>
        /// Called on client from OnClientAuthenticateInternal when a client needs to authenticate
        /// </summary>
        /// <param name="conn">Connection of the client.</param>
        public override void OnClientAuthenticate(NetworkConnection conn)
        {
            AuthRequestMessage authRequestMessage = new AuthRequestMessage {
                authUsername = username,
                authPassword = password
            };

            conn.Send(authRequestMessage);
        }
Example #9
0
 public AuthResponseMessage Authenticate(AuthRequestMessage authRequest)
 {
     return(new AuthResponseMessage()
     {
         ErrorMessage = string.Empty,
         Success = true,
         AuthenticatedIdentity = new JohnGaltIdentity()
     });
 }
 public void Auth(AuthRequest request)
 {
     if (websocket != null)
     {
         AuthRequestMessage message = new AuthRequestMessage();
         message.payload = request;
         websocket.Send(JsonUtils.serialize(message));
     }
 }
Example #11
0
        public void AuthenticationProviderSetsAuthenticatedIdentity()
        {
            var accounts        = new SampleAccountRepository();
            var authProvider    = new SrpAuthenticationProvider(accounts);
            var srpClient       = new SrpClient();
            var sessionId       = Guid.NewGuid();
            var clientEphemeral = srpClient.GenerateEphemeral();
            var request         = new Hashtable
            {
                { SrpProtocolConstants.SRP_STEP_NUMBER, 1 },
                { SrpProtocolConstants.SRP_USERNAME, UserName },
                { SrpProtocolConstants.SRP_CLIENT_PUBLIC_EPHEMERAL, clientEphemeral.Public },
            };

            var authRequest = new AuthRequestMessage
            {
                Credentials   = request,
                ClientAddress = "localhost",
                SessionID     = sessionId
            };

            var response = authProvider.Authenticate(authRequest);

            Assert.IsNotNull(response);
            Assert.IsNotNull(response.Parameters);
            Assert.IsNotNull(response.Parameters[SrpProtocolConstants.SRP_SALT]);
            Assert.IsNotNull(response.Parameters[SrpProtocolConstants.SRP_SERVER_PUBLIC_EPHEMERAL]);

            // step1 is performed
            Assert.IsTrue(authProvider.PendingAuthentications.Any());

            // server returns salt even for the unknown user name so we can't tell whether the user exists or not
            var salt = (string)response.Parameters[SrpProtocolConstants.SRP_SALT];
            var serverPublicEphemeral = (string)response.Parameters[SrpProtocolConstants.SRP_SERVER_PUBLIC_EPHEMERAL];
            var privateKey            = srpClient.DerivePrivateKey(salt, UserName, Password);
            var clientSession         = srpClient.DeriveSession(clientEphemeral.Secret, serverPublicEphemeral, salt, UserName, privateKey);

            // perform step2
            authRequest.Credentials[SrpProtocolConstants.SRP_STEP_NUMBER]          = 2;
            authRequest.Credentials[SrpProtocolConstants.SRP_CLIENT_SESSION_PROOF] = clientSession.Proof;

            // make sure that identity is set
            response = authProvider.Authenticate(authRequest);
            Assert.IsNotNull(response);
            Assert.IsNotNull(response.Parameters);
            Assert.IsNotNull(response.Parameters[SrpProtocolConstants.SRP_SERVER_SESSION_PROOF]);
            Assert.IsTrue(response.Completed);
            Assert.IsTrue(response.Success);
            Assert.IsNotNull(response.AuthenticatedIdentity);
            Assert.IsNotNull(response.AuthenticatedIdentity.IsAuthenticated);
            Assert.AreEqual(response.AuthenticatedIdentity.Name, UserName);

            var serverProof = (string)response.Parameters[SrpProtocolConstants.SRP_SERVER_SESSION_PROOF];

            srpClient.VerifySession(clientEphemeral.Public, clientSession, serverProof);
        }
        public override void OnClientAuthenticate(NetworkConnectionToServer conn)
        {
            var authRequestMessage = new AuthRequestMessage
            {
                AuthUsername = Username,
                AuthPassword = Password
            };

            manager.client.Send(authRequestMessage);
        }
Example #13
0
        // -------------------------------------------------------------------------------
        public override void OnClientAuthenticate(NetworkConnection conn)
        {
            AuthRequestMessage authRequestMessage = new AuthRequestMessage
            {
                authUsername = username,
                authPassword = GenerateHash(),
                authAction   = action
            };

            NetworkClient.Send(authRequestMessage);
        }
Example #14
0
 public void OnServerReceiveLoginMessage(NetworkConnection conn, AuthRequestMessage message)
 {
     if (message.newLogin)
     {
         InitNewAccoutLogin(conn, message.email, message.username, message.password, message.comfirmPassword);
     }
     else
     {
         InitLogin(conn, message.username, message.password);
     }
 }
 public int Auth(AuthRequest request)
 {
     if (websocket != null)
     {
         AuthRequestMessage message = new AuthRequestMessage();
         message.payload = request;
         websocket.Send(JsonUtils.serialize(message));
         return(0);
     }
     return(-1);
 }
    public override void OnClientAuthenticate(NetworkConnection conn)
    {
        string accessToken = TokenManager.singleton.accessToken;
        string groupId     = EnvironmentVariables.singleton.groupId;

        AuthRequestMessage message = new AuthRequestMessage {
            accessToken = accessToken,
            groupId     = groupId,
        };

        conn.Send(message);
    }
Example #17
0
    public override void OnClientAuthenticate(NetworkConnection conn)
    {
        // use the params to call the authenticate session ticket

        AuthRequestMessage authRequestMessage = new AuthRequestMessage
        {
            playFabID     = username,
            sessionTicket = password
        };

        NetworkClient.Send(authRequestMessage);
    }
Example #18
0
        public override void OnClientAuthenticate(INetworkPlayer player)
        {
            player.RegisterHandler <AuthResponseMessage>(OnAuthResponseMessage);

            var authRequestMessage = new AuthRequestMessage
            {
                AuthUsername = Username,
                AuthPassword = Password
            };

            player.Send(authRequestMessage);
        }
        public override void OnClientAuthenticate(NetworkConnectionToServer conn)
        {
            conn.RegisterHandler <NetworkConnectionToServer, AuthResponseMessage>(OnAuthResponseMessage, false);

            var authRequestMessage = new AuthRequestMessage
            {
                AuthUsername = Username,
                AuthPassword = Password
            };

            conn.Send(authRequestMessage);
        }
Example #20
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));
            }
        }
        public override void OnClientAuthenticate(NetworkConnection conn)
        {
            Debug.Log("Basic Auth: On Client Authenticate");

            AuthRequestMessage authRequestMessage = new AuthRequestMessage
            {
                authUsername = username,
                authPassword = password
            };

            Debug.Log("Login Message Was Sent");
            conn.Send(authRequestMessage);
        }
Example #22
0
        void OnAuthRequestMessage(NetworkConnection conn, AuthRequestMessage msg)
        {
            Debug.Log($"connection {conn.connectionId} authenticated with id {msg.clientDeviceID}");

            // Store the device id for later reference, e.g. when spawning the player
            conn.authenticationData = msg.clientDeviceID;

            // Send a response to client telling it to proceed as authenticated
            conn.Send(new AuthResponseMessage());

            // Accept the successful authentication
            ServerAccept(conn);
        }
        public async Task <AuthResponseMessage> TryAuth(Bitmap img, int timeoutMs = 30000)
        {
            var imgBytes  = ImageUtil.BytesFromBitmap(img);
            var imgBase64 = Convert.ToBase64String(imgBytes);
            var msg       = new AuthRequestMessage {
                Image = imgBase64
            };

            await SendMessage(msg);

            var resp = await WaitForRequestResponse <AuthResponseMessage>(timeoutMs, MessageType.AuthResponse);

            return(resp);
        }
        /// <summary>
        /// Called on client from OnClientAuthenticateInternal when a client needs to authenticate
        /// </summary>
        /// <param name="conn">Connection of the client.</param>
        public override async void OnClientAuthenticate(NetworkConnection conn)
        {
            ticket = await SteamUser.GetAuthSessionTicketAsync();

            if (logger.LogEnabled())
            {
                logger.LogFormat(LogType.Log, "SteamAuthenticator Got ticket!");
            }
            AuthRequestMessage authRequestMessage = new AuthRequestMessage()
            {
                steamId = SteamClient.SteamId.Value,
                ticket  = ticket.Data
            };

            NetworkClient.Send(authRequestMessage);
        }
Example #25
0
        public void UnknownUsernameReturnsSameSaltAndNewEphemeralOnEachRequest()
        {
            var accounts     = new SampleAccountRepository();
            var authProvider = new SrpAuthenticationProvider(accounts);
            var srpClient    = new SrpClient();
            var sessionId    = Guid.NewGuid();
            var request      = new Hashtable
            {
                { SrpProtocolConstants.SRP_STEP_NUMBER, 1 },
                { SrpProtocolConstants.SRP_USERNAME, "UnknownUser" },
                { SrpProtocolConstants.SRP_CLIENT_PUBLIC_EPHEMERAL, srpClient.GenerateEphemeral().Public },
            };

            var authRequest = new AuthRequestMessage
            {
                Credentials   = request,
                ClientAddress = "localhost",
                SessionID     = sessionId
            };

            var response = authProvider.Authenticate(authRequest);

            Assert.IsNotNull(response);
            Assert.IsNotNull(response.Parameters);
            Assert.IsNotNull(response.Parameters[SrpProtocolConstants.SRP_SALT]);
            Assert.IsNotNull(response.Parameters[SrpProtocolConstants.SRP_SERVER_PUBLIC_EPHEMERAL]);

            // step1 is not performed because the user is unknown
            Assert.IsFalse(authProvider.PendingAuthentications.Any());

            // server returns salt even for the unknown user name so we can't tell whether the user exists or not
            var salt1      = (string)response.Parameters[SrpProtocolConstants.SRP_SALT];
            var ephemeral1 = (string)response.Parameters[SrpProtocolConstants.SRP_SERVER_PUBLIC_EPHEMERAL];

            response = authProvider.Authenticate(authRequest);
            Assert.IsNotNull(response);
            Assert.IsNotNull(response.Parameters);
            Assert.IsNotNull(response.Parameters[SrpProtocolConstants.SRP_SALT]);
            Assert.IsNotNull(response.Parameters[SrpProtocolConstants.SRP_SERVER_PUBLIC_EPHEMERAL]);
            var salt2      = (string)response.Parameters[SrpProtocolConstants.SRP_SALT];
            var ephemeral2 = (string)response.Parameters[SrpProtocolConstants.SRP_SERVER_PUBLIC_EPHEMERAL];

            // server returns the same salt for every unknown username, but new ephemeral on each request
            Assert.AreEqual(salt1, salt2);
            Assert.AreNotEqual(ephemeral1, ephemeral2);
        }
Example #26
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);
    }
        /// <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 AuthResponseMessage Authenticate(AuthRequestMessage authRequest)
        {
            if (!authRequest.Credentials.ContainsKey("nickname"))
            {
                return new AuthResponseMessage()
                       {
                           ErrorMessage = "No valid credentials provided.",
                           Success      = false
                       }
            }
            ;

            string nickname = (string)authRequest.Credentials["nickname"];

            if (string.IsNullOrEmpty(nickname))
            {
                return new AuthResponseMessage()
                       {
                           ErrorMessage = "No nickname specified.",
                           Success      = false
                       }
            }
            ;

            if (Program.ActiveNicknames.Contains(nickname))
            {
                return new AuthResponseMessage()
                       {
                           ErrorMessage = string.Format("Nickname '{0}' is already in use.", nickname),
                           Success      = false
                       }
            }
            ;

            return(new AuthResponseMessage()
            {
                AuthenticatedIdentity = new GenericIdentity(nickname),
                Success = true
            });
        }
    }
}
Example #29
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);
            }
        }
        public override void OnClientAuthenticate(NetworkConnection conn)
        {
            string precheckStatus;

            if (!PrecheckTicket(out precheckStatus))
            {
                logger.LogFormat(LogType.Error, "Ticket failed pre-check: {0} for {1}", precheckStatus, ticketString);
                conn.isAuthenticated = false;
                // disconnect the client - doing it synchronously hangs!
                StartCoroutine(DelayedDisconnect(conn, 0.01f));
                return;
            }
            clientStatus = "Checking ticket";
            // proceed
            AuthRequestMessage authRequestMessage = new AuthRequestMessage
            {
                ticketString = ticketString
            };

            conn.Send(authRequestMessage);
        }
 public void Auth(AuthRequest request)
 {
     if (websocket != null)
     {
         AuthRequestMessage message = new AuthRequestMessage();
         message.payload = request;
         websocket.Send(JsonUtils.serialize(message));
     }
 }