Last Updated: February 25, 2016
·
1.848K
· artfulhacker

Regex-less JSONP callback validation via LINQ magic

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";

3 Responses
Add your response

This doesn't allow for foo.bar, which is valid Javascript notation and is used in projects like Angular.

over 1 year ago ·

@johnbon well thats a good point, you could easily modify it to handle that case

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

over 1 year ago ·

According to json-p.org The proposed solution, allowed syntax could include these forms:

functionName({JSON});

obj.functionName({JSON});

obj"function-name";

over 1 year ago ·