74tn9q
Last Updated: February 25, 2016
·
1.537K
· artfulhacker
10425126 10103995008712411 6222461894198440691 n

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";
Say Thanks
Respond

3 Responses
Add your response

8593
Default profile 0 normal

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

over 1 year ago ·
8597
10425126 10103995008712411 6222461894198440691 n

@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 ·
16199
E570f4ac41a8a5e732fc279cb4ff08b1

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 ·