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";
Written by Mike Olsen
Add your response
@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 == '.')))
According to json-p.org The proposed solution, allowed syntax could include these forms: