WebSync Tutorials - Frozen Mountain

WebSync 3 Tutorials


WebSync On-Demand Tutorials WebSync Server Tutorials

WebSync Server: Advanced

Take full control over your data with server-side events. In this tutorial, we will implement basic authentication.

Prerequisites

  1. You have completed the WebSync Server: Basic tutorial.
  2. You have completed the WebSync Server: Events tutorial.

Configuring your project

Before you can start coding, you need to have the correct project references.

  1. FM.WebSync.Server (available as part of WebSync Server)
  2. FM.WebSync.Core (available as part of WebSync Server)
  3. FM.WebSync.Core.Json (available as part of WebSync Server)
  4. System.Runtime.Serialization (part of the .NET framework)

Configuring the client

The client connect calls have to be modified so they include some user credentials for us to authenticate. Before sending credentials over the wire in a production environment, be sure to set up SSL/HTTPS.

client.connect({
    meta: {
        username: 'johndoe', // fake user credentials for
        password: 'password' // us to authenticate
    },
    ...
});

Performing authentication on the server

Use the WebSyncEvents class from the WebSync Server: Events tutorial and add a new method.

// a generic class that contains our WebSync events
public class WebSyncEvents
{
    [DataContract]
    private class Credentials
    {
        [DataMember(Name = "username")]
        public string Username { get; set; }
        
        [DataMember(Name = "password")]
        public string Password { get; set; }
    }

    [WebSyncEvent(EventType.BeforeConnect)]
    public static void AuthenticateConnects(object sender, WebSyncEventArgs e)
    {
        foreach (Message message in e.Messages)
        {
            // check for null credentials
            if (string.IsNullOrEmpty(message.MetaJson))
            {
                message.Successful = false;
                message.Error = "No user credentials supplied.";
            }
            else
            {
                // deserialize credentials
                Credentials credentials = JSON.Deserialize<Credentials>(message.MetaJson);

                // verify credentials (this could be replaced with a database query)
                if (credentials.Username != "johndoe" || credentials.Password != "password")
                {
                    message.Successful = false;
                    message.Error = "Invalid credentials.";
                }
            }
        }
    }
}

All connect requests will now undergo contrived credential verification. (In the real-world, the credentials would be checked against a database and not hardcoded.)

Testing

Open the page in a few browsers. Try changing the client password and refreshing the page to see the access denied.