When developing Power Pages sites, a common practice is to use JavaScript to add custom behaviours to forms or do some validation in the front-end. Which is great and simple to do.
However, we cannot rely on those for data integrity and security if this is required.
For example, if you add text field format validations using JavaScript, or limit the choices of a choice field (for example, for a Status field if you want external users to create records with status ‘Pending’ and ‘Submitted’ only and never use the values ‘Approved’, ‘Rejected’ or ‘Cancelled’), if there are no server side restrictions in place, those can be easily bypassed by someone using the browser DevTools or calling the API directly.
Dataverse Plugins to help
To prevent those hacks or bypasses from happening, we can use Dataverse plugins and the help of the IPluginExecutionContext2 interface and the property IsPortalsClientCall.
We need to register the plugin steps in the “Pre-Operation” stage (register the plugin on Create or Update messages according to your needs).
In the Plugin, you can use C# logic to validate the calls as below. If the choice value is not accepted, you can raise an exception which prevents the operation (ignore the simplicity of the code, I just want to illustrate the concept and how it works):
using System;
using Microsoft.Xrm.Sdk;
namespace PowerPagesValidationPluginSample
{
public class ValidateSupportrequestUpdates : IPlugin
{
public void Execute(IServiceProvider serviceProvider)
{
IPluginExecutionContext2 context = (IPluginExecutionContext2)serviceProvider.GetService(typeof(IPluginExecutionContext2));
if (context.IsPortalsClientCall)
{
Entity target = (Entity)context.InputParameters["Target"];
var requestStatus = target.GetAttributeValue<OptionSetValue>("pnp_requeststatus")?.Value;
//values for draft and submitted in my case
if (requestStatus != 893780000 && requestStatus != 893780001)
{
throw new InvalidPluginExecutionException(OperationStatus.Failed, 1, "You can only create records with Draft or Submitted Status");
}
}
}
}
}
For example, if you run the below Web API call (which is invalid):

You would get an exception thrown, and the record is not created (check on Dev Tools logs):

If the client-side calls do not throw any exception on the plugin, they are successfully executed.
Hope this helps you start understanding how to make your JavaScript customisations more secure in Power Pages.
References
[…] post Power Pages: Adding server-side extra validation using C# Plugins appeared first on […]
[…] the data before an update is committed. This can be done via either traditional C# plugins, as in my previous post, but also in the new Dataverse low-code plugins (currently in Preview). Even though instant […]