Regex-less JSONP callback validation via LINQ magic

Posted on

For JSONP calls we should always restrict and validate the callback parameter to prevent code injections and other hacker attacks.

To do this we usually set a max size and only allow alphanumeric characters and underscores.

Most developers would turn to regex but I prefer to do things regex-less, in C# we can validate the string <i>callback</i> as seen in this code snippet below using some LINQ magic:

if (!callback.ToCharArray().All(c => Char.IsLetter(c) || Char.IsNumber(c) || c == '_')))

    return "illegal callback, can only contain alphanumeric characters and underscores";

Leave a Reply

Your email address will not be published.