| WebSync On-Demand Tutorials | WebSync Server Tutorials |
|---|---|
|
|
|
Take full control over your data with server-side events. In this tutorial, we will implement basic authentication.
Before you can start coding, you need to have the correct project references.
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
},
...
});
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.)
Open the page in a few browsers. Try changing the client password and refreshing the page to see the access denied.